我正在学习 Windows 操作系统,并且正在编写标准的消费者生产者问题。我有一个用于资源计数的信号量和一个用于同步的 Mutex。我在 CreateSemaphore() 中传递了 max count 50 的值,所以它不应该允许生产者创建超过 50 个资源。但是当我运行代码时,它远不止于此。我是否错误地理解了 max count 参数的使用?我也在粘贴代码。请帮我解决这个问题。
#include<stdio.h>
#include<windows.h>
DWORD WINAPI consumerThread(LPVOID args);
DWORD WINAPI producerThread(LPVOID args);
int shared;
HANDLE hMutex;
HANDLE hSemaphore;
HANDLE hConsumer;
HANDLE hProducer;
DWORD dwConsumerId,dwProducerId;
#define MAX_COUNT 50
#define MIN_COUNT 0
int main()
{
if(!(hMutex=CreateMutex(NULL,0,NULL)))
{
puts("Error:: unable to create Mutex!!");
ExitProcess(GetLastError());
}
if(!(hSemaphore=CreateSemaphore(NULL,MIN_COUNT,MAX_COUNT,NULL)))
{
puts("Error:: unable to create Semaphore object!!");
ExitProcess(GetLastError());
}
if(!(hConsumer=CreateThread(NULL,0,consumerThread,NULL,0,&dwConsumerId)))
{
puts("Error:: unable to create consumer Thread!!");
ExitProcess(GetLastError());
}
if(!(hProducer=CreateThread(NULL,0,producerThread,NULL,0,&dwProducerId)))
{
puts("Error:: unable to create producer Thread!!");
ExitProcess(GetLastError());
}
WaitForSingleObject(hConsumer,INFINITE);
WaitForSingleObject(hProducer,INFINITE);
CloseHandle(hMutex);
CloseHandle(hSemaphore);
CloseHandle(hConsumer);
CloseHandle(hProducer);
return 0;
}
DWORD WINAPI consumerThread(LPVOID args)
{
while(1)
{
WaitForSingleObject(hSemaphore,INFINITE);
WaitForSingleObject(hMutex,INFINITE);
shared--;
printf("Consumer = %d\n",shared);
ReleaseMutex(hMutex);
//Sleep(1000);
}
}
DWORD WINAPI producerThread(LPVOID args)
{
if(!SetThreadPriority(hProducer,THREAD_PRIORITY_HIGHEST))
{
printf("Error:: Unable to set the thread priority level!!\n");
ExitProcess(GetLastError());
}
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
shared++;
printf("Producer =%d\n",shared);
ReleaseMutex(hMutex);
ReleaseSemaphore(hSemaphore,1,NULL);
}
}