本文主要是介绍多线程第八篇:生产者消费者问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
著名的生产者消费者问题,用到同步和互斥.
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,证明消费者在缓冲区满的情况下是不放的.
这篇关于多线程第八篇:生产者消费者问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!