イベントを使用して生産者と消費者の問題のコードを書きました。そして問題は、消費者スレッドが生産者スレッドを引き継いでおり、デッドロックの状態にあることです。ただし、コードはミューテックスで正常に動作しています。正確にどこに問題があるか教えてください。
最大バッファ サイズは 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]);
}
}