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

著名的生产者消费者问题,用到同步和互斥.

  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值