生產者消費者C++實現
#include<string>
#include<iostream>
#include<process.h>
#include<windows.h>
#include <stdlib.h>
#include<time.h>
#include<list>
using namespace std;
HANDLE empty,full; //同步訊號量 緩衝池的剩餘 緩衝池中的產品個數 生產者與消
費者同步
HANDLE mutex;//互斥訊號量,生產者與生產者互斥,消費者與消費者互斥
int buf_max=5; //緩衝池大小
int product=0; //產品數量
typedef list<int> LISTINT;
LISTINT Buffer;
LISTINT::iterator i;
int getRandom()
{
return rand()%23;
}
void printBuffer()
{
cout<<"現在緩衝池中有:";
for (i = Buffer.begin(); i != Buffer.end(); ++i)
cout << *i << ",";
cout<<endl;
}
//生產者執行緒
unsigned __stdcall threadProducer(void *)
{
for(int i = 0; i < 5; i++){
Sleep(getRandom()*10);
WaitForSingleObject(empty, INFINITE);//等待同步訊號量empty
WaitForSingleObject(mutex, INFINITE);//等待互斥訊號量mutex
product++;
int p=getRandom();
Buffer.push_front(p);
cout<<"生產者生產了"<<p<<" ";
printBuffer();
Sleep(100);
ReleaseSemaphore(mutex, 1, NULL);//釋放互斥訊號量mutex
ReleaseSemaphore(full, 1, NULL);//釋放同步訊號量full
}
return 1;
}
//消費者執行緒
unsigned __stdcall threadConsumer(void *)
{
for(int i = 0; i < 5; i++){
Sleep(getRandom()*10);
WaitForSingleObject(full, INFINITE);//等待同步訊號量full
WaitForSingleObject(mutex, INFINITE);//等待互斥訊號量mutex
product--;
cout<<"消費者消費了產品"<<Buffer.back()<<" ";
Buffer.pop_back();
printBuffer();
Sleep(100);
ReleaseSemaphore(mutex, 1, NULL);//釋放互斥訊號量mutex
ReleaseSemaphore(empty, 1, NULL);//釋放訊號量
}
return 2;
}
void main()
{
bool flag=false;
while(!flag)
{
cout<<"緩衝池大小為"<<buf_max<<endl;
if(buf_max<=0);
else flag=true;
}
//建立訊號量
empty = CreateSemaphore(NULL, buf_max, buf_max, NULL);//初值為緩衝池大
小,最大為緩衝池大小
full = CreateSemaphore(NULL, 0, buf_max, NULL); //初值為0,最大
為緩衝池大小
mutex = CreateSemaphore(NULL,1,1,NULL); //初值為1,最大為
1
HANDLE hth1, hth2; //執行緒控制代碼
//建立執行緒
hth1 = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)
threadProducer, NULL, 0, NULL);//生產者執行緒
hth2 = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)
threadConsumer, NULL, 0, NULL);//消費者執行緒
//等待子執行緒結束
WaitForSingleObject(hth1, INFINITE);
WaitForSingleObject(hth2, INFINITE);
//關閉控制代碼
CloseHandle(hth1);
CloseHandle(hth2);
CloseHandle(empty);
CloseHandle(full);
CloseHandle(mutex);
}