理发师
来源:互联网 发布:孙子兵法华杉 知乎 编辑:程序博客网 时间:2024/05/01 00:15
#include <Windows.h>#include <iostream>using namespace std;const int c_WaitChairCount = 5;HANDLE hSemWaitChair = NULL;HANDLE hMutexBarChair = NULL;HANDLE hSemReady = NULL;HANDLE hSemDone = NULL;HANDLE hMutexCount = NULL;int count = 0;DWORD WINAPI barber(){ while (true) { cout << "理发师等待顾客来理发" << endl; WaitForSingleObject(hSemReady, INFINITE); cout << "理发师开始理发...." << endl; Sleep(2000); ReleaseSemaphore(hSemDone, 1, NULL); cout << "理发完成" << endl; }}DWORD WINAPI consumer(LPVOID para){ int c = (int)para; cout << "\n\t\t顾客 " << c << " 来了->" << endl; WaitForSingleObject(hMutexCount, INFINITE); if (count < c_WaitChairCount) { count += 1; cout << "\t\t有空椅子,顾客 " << c << " 坐上空椅子,等待理发" << endl; ReleaseMutex(hMutexCount); } else { cout << "\t\t没有空椅子,顾客 " << c << "离开了...." << endl; ReleaseMutex(hMutexCount); } WaitForSingleObject(hSemWaitChair, INFINITE); WaitForSingleObject(hMutexBarChair, INFINITE); cout << "\t\t顾客 " << c << " 坐上理发椅,开始理发吧" << endl; ReleaseSemaphore(hSemWaitChair, 1, NULL); ReleaseSemaphore(hSemReady, 1, NULL); WaitForSingleObject(hSemDone, INFINITE); ReleaseMutex(hMutexBarChair); WaitForSingleObject(hMutexCount, INFINITE); count -= 1; cout << "\t\t顾客 " << c << " 理发完成, 帅呆的离开了。。。" << endl; ReleaseMutex(hMutexCount); return 0;}int main(int argc, char *argv[]){ hSemWaitChair = CreateSemaphore(NULL, c_WaitChairCount, c_WaitChairCount, NULL); hMutexBarChair = CreateMutex(NULL, false, NULL); hSemReady = CreateSemaphore(NULL, 0, 1, NULL); hSemDone = CreateSemaphore(NULL, 0, 1, NULL); hMutexCount = CreateMutex(NULL, false, NULL); HANDLE hBarber = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)barber, NULL, 0, NULL); CloseHandle(hBarber); int i = 0; while (true) { HANDLE hCustomer = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)consumer, (LPVOID)(i++), 0, NULL); CloseHandle(hCustomer); // 每1秒 来一个顾客 Sleep(1000); } getchar(); return 0;}
阅读全文
1 0
- 《理发师》
- 理发师
- 理发师问题
- 理发师问题
- 理发师悖论
- 理发师问题
- 理发师悖论
- 理发师问题
- 理发师问题
- PV----------理发师
- 理发师问题
- 理发师该怎么说?
- 睡眠理发师问题
- 睡眠理发师问题
- 理发师悖论与集合
- 困睡的理发师
- 睡眠理发师问题
- 信号量实现理发师问题
- 216. Combination Sum III
- Android--Socket通信
- bingo-培训——用户体验
- 盘点8种CSS实现垂直居中水平居中的绝对定位居中技术
- ubunut python2 和python 3 同时存在 pip指向问题
- 理发师
- oracel 中关于时间日期的取值和转化
- 微信小程序 同步请求授权
- SpringData JPA中数据库表的映射类需要一个不在表中的字段
- 学习笔记第一篇,不喜勿喷
- a、b交换
- 欢迎使用CSDN-markdown编辑器
- Android Device Monitor 文件管理的常见问题
- 石乙己——孔乙己程序员版