博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者消费者C++实现
阅读量:5142 次
发布时间:2019-06-13

本文共 2124 字,大约阅读时间需要 7 分钟。

#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

你可能感兴趣的文章