火车票线程同步互斥体实现
Posted YuRi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了火车票线程同步互斥体实现相关的知识,希望对你有一定的参考价值。
##占位
#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); }
以上是关于火车票线程同步互斥体实现的主要内容,如果未能解决你的问题,请参考以下文章