*注:(此代码必背)
##
#include <windows.h> #include <iostream> int tickets = 100; HANDLE hMutex; DWORD WINAPI FunProc1(LPVOID param) { while (TRUE) { WaitForSingleObject(hMutex, INFINITE); if (tickets > 0) { std::cout << "thread1 sell ticket:" << tickets-- << std::endl; } else break; ReleaseMutex(hMutex); } return 0; } DWORD WINAPI FunProc2(LPVOID param) { while (TRUE) { WaitForSingleObject(hMutex, INFINITE); if (tickets > 0) { std::cout << "thread2 sell ticket:" << tickets-- << std::endl; } else break; ReleaseMutex(hMutex); } return 0; } int main() { HANDLE hThread1, hThread2; hMutex = CreateMutex(NULL, FALSE, NULL);//创建互斥体的线程(也就是此主线程)不拥有 //互斥对象,操作系统会将计数置为0,设为有信号状态。 hThread1 = CreateThread(NULL, 0, FunProc1, NULL, 0, NULL); hThread2 = CreateThread(NULL, 0, FunProc2, NULL, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); Sleep(4000); }
注释:
在创建互斥对象时,第二个参数为FALSE值,表明当前没有线程拥有这个互斥对象,于是操作系统就会将该互斥对象设置为有信号状态。