#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);}