多线程第八篇:生产者消费者问题

来源:互联网 发布:matlab subs 矩阵 编辑:程序博客网 时间:2024/05/26 02:20
著名的生产者消费者问题,用到同步和互斥.

  1.我们假设缓冲区大小为2,即最多只能放2个资源,并且肯定大于0.
  2.生产者和消费者是可以同时进入缓冲区的.


代码设计:
1.由于window信号量在缓冲区满的时候无法阻塞,所以需要两个信号量,分别表示缓冲区剩余资源和可用资源分别用于阻塞消费者和生产者.
2.对于全局资源的存取,所有线程都要互斥.
3.对于消费者和生产者来说分别互斥自己的代码.
 

OK上代码:(相当easy)
#include <iostream>#include <windows.h>#include <process.h>int g_count = 0;CRITICAL_SECTION producer_critical, consumer_critical;HANDLE producer_semaphore ,consumer_semaphore;CRITICAL_SECTION all;unsigned int __stdcall producer(void *){       int i =0;    while ( i<5 ){        WaitForSingleObject(consumer_semaphore ,INFINITE);        EnterCriticalSection(&producer_critical );        std::cout <<"生产者生产了."<<std ::endl;        ++ i;              EnterCriticalSection(&all );        std::cout <<"生产者"<<++ g_count<<std ::endl;        LeaveCriticalSection(&all );        ReleaseSemaphore(producer_semaphore ,1,NULL);        LeaveCriticalSection(&producer_critical );    }        return 0;}unsigned int __stdcall consumer(void *){        int i =0;    while ( i<5 ){        WaitForSingleObject(producer_semaphore ,INFINITE);        EnterCriticalSection(&consumer_critical );        std::cout <<"消费者消费了."<<std ::endl;        ++ i;        EnterCriticalSection(&all );        std::cout <<"消费者"<<-- g_count<<std ::endl;        LeaveCriticalSection(&all );        ReleaseSemaphore(consumer_semaphore ,1,NULL);        LeaveCriticalSection(&consumer_critical );    }       return 0;}int main (){    InitializeCriticalSection(& producer_critical);    InitializeCriticalSection(& consumer_critical);    InitializeCriticalSection(& all);    producer_semaphore = CreateSemaphore(NULL ,0,2,NULL);    consumer_semaphore = CreateSemaphore(NULL ,2,2,NULL);    HANDLE hproducer = (HANDLE )_beginthreadex( NULL,0,producer ,NULL,0, NULL);    HANDLE hconsumer = (HANDLE )_beginthreadex( NULL,0,consumer ,NULL,0, NULL);     WaitForSingleObject( hproducer,INFINITE );    WaitForSingleObject( hconsumer,INFINITE );    CloseHandle( hproducer);    CloseHandle( hconsumer);    return 0;}  

 
看出来上述结果说明的问题了吗???
我们来分析一下:
1.生产者和消费者执行的代码并不是互斥的(除了对全局资源的控制:EnterCriticalSection (&all );)
 
2.数字总是大于0,证明消费者总是在有资源的情况下采取的,而小于3,证明消费者在缓冲区满的情况下是不放的.


0 0
原创粉丝点击