以下是一个简单的睡眠理发师问题的 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` 函数用于让顾客线程之间的到达时间有所区别。