用信号量机制解决生产者消费者问题,要求:在windows环境下完成;使用c++语言;每个生产者和消费者对有界缓冲区进行操作后,即时显示有界缓冲区的全部内容,当前指针位置和生产者消费者线程的标识符;生产者有三个,消费者有五个,多个生产者或多个消费者之间须有共享对缓冲区进行操作的函数代码;有界缓冲区设有20个存储单元,写入或取出的数据项设定为1-20这20个整型数
时间: 2024-02-13 14:01:09 浏览: 64
编程实现生产者消费者或读写者的同步问题
4星 · 用户满意度95%
好的,这是一个稍微复杂一些的生产者消费者问题,需要更多的生产者和消费者,并且需要共享对缓冲区进行操作的函数代码。
以下是一个满足您要求的实现:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <Windows.h>
using namespace std;
const int BUFFER_SIZE = 20;
queue<int> buffer;
int producer_id = 0;
int consumer_id = 0;
mutex mtx;
condition_variable not_full_cv;
condition_variable not_empty_cv;
int in = 0;
int out = 0;
int count = 0;
void produce(int id)
{
while (true)
{
unique_lock<mutex> lock(mtx);
while (count == BUFFER_SIZE)
{
not_full_cv.wait(lock);
}
int item = ++in;
buffer.push(item);
cout << "Producer " << id << " produces item " << item << endl;
count++;
cout << "Current buffer: ";
for (int i : buffer)
{
cout << i << " ";
}
cout << endl;
cout << "Current in: " << in << endl;
cout << "Current producer: " << producer_id << endl;
not_empty_cv.notify_all();
lock.unlock();
Sleep(1000);
}
}
void consume(int id)
{
while (true)
{
unique_lock<mutex> lock(mtx);
while (count == 0)
{
not_empty_cv.wait(lock);
}
int item = buffer.front();
buffer.pop();
cout << "Consumer " << id << " consumes item " << item << endl;
count--;
cout << "Current buffer: ";
for (int i : buffer)
{
cout << i << " ";
}
cout << endl;
cout << "Current out: " << out << endl;
cout << "Current consumer: " << consumer_id << endl;
not_full_cv.notify_all();
lock.unlock();
Sleep(1000);
}
}
void producer_consumer()
{
while (true)
{
unique_lock<mutex> lock(mtx);
while (count == 0)
{
not_empty_cv.wait(lock);
}
int item = buffer.front();
buffer.pop();
count--;
lock.unlock();
int result = item * item;
lock.lock();
buffer.push(result);
count++;
cout << "Producer-Consumer produces item " << result << endl;
cout << "Current buffer: ";
for (int i : buffer)
{
cout << i << " ";
}
cout << endl;
cout << "Current in: " << in << endl;
cout << "Current out: " << out << endl;
cout << "Current producer: " << producer_id << endl;
cout << "Current consumer: " << consumer_id << endl;
not_full_cv.notify_all();
lock.unlock();
Sleep(1000);
}
}
int main()
{
thread p1(produce, ++producer_id);
thread p2(produce, ++producer_id);
thread p3(produce, ++producer_id);
thread c1(consume, ++consumer_id);
thread c2(consume, ++consumer_id);
thread c3(consume, ++consumer_id);
thread c4(consume, ++consumer_id);
thread c5(consume, ++consumer_id);
thread pc(producer_consumer);
p1.join();
p2.join();
p3.join();
c1.join();
c2.join();
c3.join();
c4.join();
c5.join();
pc.join();
return 0;
}
```
这个实现和之前的实现相似,不同之处在于增加了一个函数 producer_consumer,用于实现生产者消费者之间的合作。这个函数会从缓冲区中取出一个数据项,并计算其平方,然后将结果加入缓冲区。
在主函数中,创建了三个生产者线程和五个消费者线程,以及一个 producer_consumer 线程,并等待它们结束。
希望这个代码可以满足您的需求!
阅读全文