0

我已经使用事件为生产者消费者问题编写了代码。问题是消费者线程正在接管生产者线程并且它处于死锁状态。但是代码与互斥锁一起工作正常。请让我知道问题到底出在哪里。

我假设最大缓冲区大小为 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]);

       }

 }
4

1 回答 1

1

datanew永远不会分配您的全局互斥量句柄。在main()您将互斥锁分配给名为 的局部变量datanew,而不是全局变量datanew。所以producer()consumer()没有同步。

从main() 中HANDLE的行中删除。HANDLE datanew=CreateEvent(NULL,TRUE,TRUE,NULL);

于 2013-07-13T17:24:08.097 回答