#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
class ReadQueue {
public:
void enqueue(int value) {
std::lock_guard<std::mutex> lock(mtx);
queue.push(value);
cond.notify_one(); // Notify one waiting thread
}
int dequeue() {
std::unique_lock<std::mutex> lock(mtx);
cond.wait(lock, [this] { return !queue.empty(); }); // Wait until the queue is not empty
int value = queue.front();
queue.pop();
return value;
}
private:
std::queue<int> queue;
std::mutex mtx;
std::condition_variable cond;
};
void producer(ReadQueue& q, int num_items) {
for (int i = 0; i < num_items; ++i) {
q.enqueue(i);
std::cout << "Produced: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate work
}
}
void consumer(ReadQueue& q, int num_items) {
for (int i = 0; i < num_items; ++i) {
int value = q.dequeue();
std::cout << "Consumed: " << value << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(150)); // Simulate work
}
}
int main() {
ReadQueue q;
const int num_items = 10;
std::thread t1(producer, std::ref(q), num_items);
std::thread t2(consumer, std::ref(q), num_items);
t1.join();
t2.join();
return 0;
}
类 ReadQueue
:
std::queue
来存储数据。std::mutex
来保证线程安全。std::condition_variable
来实现生产者和消费者之间的同步。方法 enqueue
:
方法 dequeue
:
函数 producer
和 consumer
:
producer
函数模拟生产者,向队列中添加数据。consumer
函数模拟消费者,从队列中取出数据。主函数 main
:
ReadQueue
对象。producer
和 consumer
函数。join
方法等待两个线程结束。上一篇:c++ 面向对象
下一篇:c++运算符优先级由高到低
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站