JAVA睡眠理发师代码记录

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的睡眠理发师问题的 C 语言代码,可以在 Windows 系统上运行: ``` #include <stdio.h> #include <windows.h> int main() { HANDLE hSemaphore; // 信号量句柄 int i; // 创建信号量 hSemaphore = CreateSemaphore(NULL, 2, 2, NULL); if (hSemaphore == NULL) { printf("CreateSemaphore failed (%d)\n", GetLastError()); return 1; } // 创建理发师线程 HANDLE hBarberThread = CreateThread(NULL, 0, BarberThread, &hSemaphore, 0, NULL); if (hBarberThread == NULL) { printf("CreateThread failed (%d)\n", GetLastError()); return 1; } // 创建顾客线程 HANDLE hCustomerThread[10]; for (i = 0; i < 10; i++) { hCustomerThread[i] = CreateThread(NULL, 0, CustomerThread, &hSemaphore, 0, NULL); if (hCustomerThread[i] == NULL) { printf("CreateThread failed (%d)\n", GetLastError()); return 1; } Sleep(1000); } // 等待线程结束 WaitForSingleObject(hBarberThread, INFINITE); for (i = 0; i < 10; i++) { WaitForSingleObject(hCustomerThread[i], INFINITE); } // 关闭句柄 CloseHandle(hSemaphore); CloseHandle(hBarberThread); for (i = 0; i < 10; i++) { CloseHandle(hCustomerThread[i]); } return 0; } DWORD WINAPI BarberThread(LPVOID lpParam) { HANDLE hSemaphore = *(HANDLE*)lpParam; while (TRUE) { printf("Barber is sleeping...\n"); WaitForSingleObject(hSemaphore, INFINITE); // 获取信号量 printf("Barber is cutting hair...\n"); Sleep(1000); ReleaseSemaphore(hSemaphore, 1, NULL); // 释放信号量 } return 0; } DWORD WINAPI CustomerThread(LPVOID lpParam) { HANDLE hSemaphore = *(HANDLE*)lpParam; printf("Customer %d comes in...\n", GetCurrentThreadId()); WaitForSingleObject(hSemaphore, INFINITE); // 获取信号量 printf("Customer %d is getting a haircut...\n", GetCurrentThreadId()); Sleep(1000); ReleaseSemaphore(hSemaphore, 1, NULL); // 释放信号量 printf("Customer %d leaves.\n", GetCurrentThreadId()); return 0; } ``` 代码中使用了 Windows API 的信号量机制来实现对睡眠理发师问题的模拟。其中,`CreateSemaphore` 函数创建一个信号量,第二个参数指定初始计数值为 2(即有两个空闲椅子),第三个参数指定最大计数值也为 2,第四个参数为 NULL 表示不使用命名信号量。`WaitForSingleObject` 函数和 `ReleaseSemaphore` 函数分别用于获取和释放信号量。`CreateThread` 函数创建线程。`Sleep` 函数用于让顾客线程之间的到达时间有所区别。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值