// Mutex.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #include <iostream> using namespace std; DWORD WINAPI Func1Proc(LPVOID lpParam); DWORD WINAPI Func2Proc(LPVOID lpParam); static int tickets = 100; HANDLE m_hMutex; int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread1; HANDLE hThread2; hThread1 = CreateThread(NULL, 0, Func1Proc, NULL, 0, NULL); hThread2 = CreateThread(NULL, 0, Func2Proc, NULL, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); m_hMutex = CreateMutex(NULL, FALSE, L"tickets"); // 如果为TRUE,则此互斥量被主线程占用,需要调用 ReleaseMutex(m_hMutex); getchar(); CloseHandle(m_hMutex); return 0; } DWORD WINAPI Func1Proc(LPVOID lpParameter) { while (TRUE) { WaitForSingleObject(m_hMutex, INFINITE); if (tickets > 0) { Sleep(300); cout<<"Thread1 sell tickets:"<<tickets--<<endl; } else { break; } ReleaseMutex(m_hMutex); } return 0; } DWORD WINAPI Func2Proc(LPVOID lpParameter) { while (TRUE) { WaitForSingleObject(m_hMutex, INFINITE); if (tickets > 0) { Sleep(1); cout<<"Thread2 sell tickets:"<<tickets--<<endl; } else { break; } ReleaseMutex(m_hMutex); } return 0; }
一个简单的多线程例子-互斥量
最新推荐文章于 2020-08-19 21:13:43 发布