我已经使用事件为生产者消费者问题编写了代码。问题是消费者线程正在接管生产者线程并且它处于死锁状态。但是代码与互斥锁一起工作正常。请让我知道问题到底出在哪里。
我假设最大缓冲区大小为 50。
#include<stdio.h>
#include<Windows.h>
#include<WinBase.h>
int Buffersize=0;
HANDLE datanew;
void producer()
{
while(1)
{
if(Buffersize==50)
{
Sleep(1000);
}
printf("\n Inside the producer routine ");
Buffersize++;
printf("\n Number of Items in the buffer = %d",Buffersize);
SetEvent(datanew);
}
}
void consumer()
{
while(1)
{
if(Buffersize==0)
{
Sleep(1000);
}
printf("\n Inside the consumer routine ");
if (WaitForSingleObject(datanew,INFINITE) == WAIT_OBJECT_0){
Buffersize--;
ResetEvent(datanew);
printf("\n Number of Items in the buffer = %d",Buffersize);
}
}
int main()
{
DWORD idprod,idcons;
HANDLE datanew=CreateEvent(NULL,TRUE,TRUE,NULL);
HANDLE threadarray[2];
HANDLE prodhnd=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)producer,0,0,&idprod);
HANDLE conshnd=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)consumer,0,0,&idcons);
threadarray[0]=prodhnd;
threadarray[1]=conshnd;
WaitForMultipleObjects(2,threadarray, TRUE, INFINITE);
for(int i=0; i<2; i++)
{
CloseHandle(threadarray[i]);
}
}