火車票線程同步(一)互斥體實現
阿新 • • 發佈:2017-10-22
eas 火車票 oid 主線程 ## code api 火車 ram
##占位
#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); }
火車票線程同步(一)互斥體實現