以下代码用来演示semaphore控制多线程,停车场的车位数模拟semaphore对象数,汽车模拟线程:
#include <stdio.h>
#include<windows.h>
struct Car {
char name[20];
DWORD time;
};
DWORD WINAPI ThreadProc(LPVOID lpThreadParameter);
HANDLE hSemaphore = INVALID_HANDLE_VALUE;
int main()
{
HANDLE hThread[5] = { INVALID_HANDLE_VALUE };
hSemaphore = CreateSemaphore(NULL, 3, 3, L"Car Park");
int i;
for (i = 0; i < 5; ++i)
{
Car *pCar = new Car;
sprintf(pCar->name, "Car %c", 'A' + i);
pCar->time = 3 + i * 2;
hThread[i] = CreateThread(NULL, 0, ThreadProc, (LPVOID)pCar, 0, NULL);
}
WaitForMultipleObjects(5, hThread, true, INFINITE);
}
DWORD WINAPI ThreadProc(LPVOID lpThreadParameter)
{
WaitForSingleObject(hSemaphore, INFINITE);
Car *pCar = (Car*)lpThreadParameter;
printf("%s enter and stay %d seconds\n", pCar->name, pCar->time);
Sleep(pCar->time * 1000);
printf("%s leave \n", pCar->name);
ReleaseSemaphore(hSemaphore, 1, NULL);
return 0;
}
由于线程是同步运行,因此每次运行结果可能有差异。