生产者消费者计划的僵局

时间:2013-07-13 17:07:35

标签: c multithreading winapi

我已经使用事件为生产者消费者问题编写了代码。问题是消费者线程正在接管生产者线程并且处于死锁状态。但是代码在使用互斥锁时工作正常。请告诉我问题的确切位置。

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

       }

 }

1 个答案:

答案 0 :(得分:1)

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

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