利用C++实现生产者消费者图形化演示
时间: 2023-07-11 15:04:59 浏览: 117
生产者消费者图形化演示
5星 · 资源好评率100%
生产者消费者问题是一个经典的并发编程问题,可以通过多线程来实现。下面是一个基于C++的生产者消费者图形化演示程序的简单实现:
```
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <vector>
#include <SFML/Graphics.hpp>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
const int BUFFER_SIZE = 5;
const int PRODUCER_NUM = 2;
const int CONSUMER_NUM = 2;
const int ITEM_SIZE = 20;
const int ITEM_GAP = 10;
const int ITEM_ROW_GAP = 50;
const int ITEM_COL_GAP = 10;
const int ITEM_START_X = 30;
const int ITEM_START_Y = 100;
struct Item {
int id;
sf::RectangleShape shape;
Item(int id) : id(id) {
shape.setSize(sf::Vector2f(ITEM_SIZE, ITEM_SIZE));
shape.setFillColor(sf::Color::Green);
shape.setOutlineThickness(2);
shape.setOutlineColor(sf::Color::Cyan);
}
void setPosition(int x, int y) {
shape.setPosition(sf::Vector2f(x, y));
}
};
std::queue<Item> buffer;
std::mutex mutex;
std::condition_variable not_full;
std::condition_variable not_empty;
bool done = false;
void producer(int id) {
while (!done) {
std::unique_lock<std::mutex> lock(mutex);
not_full.wait(lock, []{ return buffer.size() < BUFFER_SIZE; });
Item item(buffer.size() + 1);
item.setPosition(ITEM_START_X + (ITEM_SIZE + ITEM_GAP) * buffer.size(),
ITEM_START_Y + ITEM_ROW_GAP * id + ITEM_COL_GAP * id);
buffer.push(item);
not_empty.notify_all();
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
void consumer(int id) {
while (!done) {
std::unique_lock<std::mutex> lock(mutex);
not_empty.wait(lock, []{ return !buffer.empty(); });
buffer.pop();
not_full.notify_all();
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
int main() {
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Producer-Consumer Demo");
std::vector<std::thread> producers;
std::vector<std::thread> consumers;
for (int i = 0; i < PRODUCER_NUM; i++) {
producers.emplace_back(producer, i);
}
for (int i = 0; i < CONSUMER_NUM; i++) {
consumers.emplace_back(consumer, i);
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
done = true;
}
}
window.clear(sf::Color::White);
std::unique_lock<std::mutex> lock(mutex);
for (auto& item : buffer) {
window.draw(item.shape);
}
lock.unlock();
window.display();
}
for (auto& producer : producers) {
producer.join();
}
for (auto& consumer : consumers) {
consumer.join();
}
return 0;
}
```
这个程序使用 SFML 库来实现图形化界面,其中 `Item` 结构体表示生产者生产的物品,包含一个 ID 和一个矩形形状。生产者线程在等待缓冲区不满时生产物品并将其加入缓冲区,然后通知消费者线程。消费者线程在等待缓冲区不空时从中取出一个物品并通知生产者线程。主线程循环绘制缓冲区中的物品,并在接收到关闭窗口事件时结束生产者消费者线程的运行。
阅读全文