- #include <windows.h>
- #include <iostream>
- DWORD WINAPI ThreadProc1(LPVOID lpParameter );
- DWORD WINAPI ThreadProc2(LPVOID lpParameter );
- int index = 0;
- int tickets = 100;
- HANDLE hMutex;
- int main()
- {
- HANDLE hThread1 ;
- HANDLE hThread2 ;
- /*hMutex = CreateMutex(NULL,true,NULL);
- WaitForSingleObject(hMutex,0);
- ReleaseMutex(hMutex);
- ReleaseMutex(hMutex);
- */
- hMutex = CreateMutex(NULL,true,"tickets");
- //使程序只有一个运行实例
- if(hMutex)
- {
- if(ERROR_ALREADY_EXISTS == GetLastError())
- {
- std::cout<<"Only one instance can be ran!"<<std::endl;
- return 0;
- }
- }
- hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
- hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- ReleaseMutex(hMutex);
- /*while(index++<1000)
- std::cout<<"The main thread is running"<<std::endl;*/
- //Sleep(10);
- Sleep(4000);
- return 0;
- }
- DWORD WINAPI ThreadProc1(LPVOID lpParameter )
- {
- while(true)
- {
- WaitForSingleObject(hMutex,INFINITE);
- if(tickets)
- {
- std::cout<<"Thread1 selled tickets "<<tickets--<<std::endl;
- }
- else
- break;
- ReleaseMutex(hMutex);
- }
- return 0;
- }
- DWORD WINAPI ThreadProc2(
- LPVOID lpParameter // thread data
- )
- {
- while(true)
- {
- WaitForSingleObject(hMutex,INFINITE);
- if(tickets)
- {
- std::cout<<"Thread2 selled tickets "<<tickets--<<std::endl;
- }
- else
- break;
- ReleaseMutex(hMutex);
- }
- return 0;
- }
用mutex同步多线程
最新推荐文章于 2022-08-04 14:09:32 发布