#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); }
原文链接: https://www.cnblogs.com/lancelee98/p/9918332.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/284418
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!