卖车票多线程示例--互斥对象

//多线程卖车票 | 互斥对象 #include<windows.h> #include<iostream.h> int index=0; int tickets=100; HANDLE hMutex; DWORD WINAPI Thread1Proc(LPVOID lpParameter) { while(TRUE)//保证线程的不断执行 { WaitForSingleObject(hMutex,INFINITE);//获取互斥对象 if(tickets>0) { Sleep(1); cout<<"thread1 sells ticket:"<<tickets--<<endl; } else break; ReleaseMutex(hMutex);//释放对互斥对象的拥有权 } return 0; } DWORD WINAPI Thread2Proc(LPVOID lpParameter) { while(TRUE) { WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { Sleep(2); cout<<"thread2 sells ticket:"<<tickets--<<endl; } else break; ReleaseMutex(hMutex); } return 0; } void main() { HANDLE hThread1; HANDLE hThread2; /* 注意,创新互斥器放在创建线程之前 */ hMutex=CreateMutex(NULL,TRUE,NULL);//TRUE表示调用CreateMutex的线程(即主线程)拥有了互斥对象 hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL); hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL); CloseHandle(hThread1);//关闭句柄,此时系统会递减新线程的线程内核对象的使用计数,当创建的线程 CloseHandle(hThread2);//执行完毕后,系统也会递减线程内核对象的使用计数,计数为0时,系统释放线程内核对象 ReleaseMutex(hMutex);//主线程释放互斥对象的拥有权 Sleep(10000);//要保证在卖完100张票前,主线程不能退出 }

你可能感兴趣的:(thread,多线程,null,winapi)