阻塞队列是C++多线程中实现生产者-消费者模型的基础工具,通过std::queue、std::mutex和std::condition_variable保证线程安全与阻塞同步,支持固定容量的FIFO数据传递,可用于高效解耦生产与消费过程。

在C++多线程编程中,阻塞队列是一种常用的线程安全数据结构,用于在线程之间传递任务或数据。它结合了队列的先进先出(FIFO)特性与线程同步机制,当队列为空时,消费者线程会自动阻塞等待;当队列满时,生产者线程也会阻塞,直到有空间可用。这种机制非常适合实现生产者-消费者模型。
要实现一个基本的阻塞队列,需要以下几个关键元素:
下面是一个线程安全、支持阻塞操作的C++模板类实现:
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
template<typename T>
class BlockingQueue {
private:
std::queue<T> data_queue;
mutable std::mutex mtx;
std::condition_variable not_empty;
std::condition_variable not_full;
size_t max_size;
public:
explicit BlockingQueue(size_t max = 1000) : max_size(max) {}
void put(const T& value) {
std::unique_lock<std::mutex> lock(mtx);
not_full.wait(lock, [this] { return data_queue.size() < max_size; });
data_queue.push(value);
not_empty.notify_one();
}
void take(T& value) {
std::unique_lock<std::mutex> lock(mtx);
not_empty.wait(lock, [this] { return !data_queue.empty(); });
value = data_queue.front();
data_queue.pop();
not_full.notify_one();
}
bool empty() const {
std::lock_guard<std::mutex> lock(mtx);
return data_queue.empty();
}
size_t size() const {
std::lock_guard<std::mutex> lock(mtx);
return data_queue.size();
}
};
这个实现中,put 方法在队列满时会等待 not_full 条件成立,take 方法在队列空时等待 not_empty 成立。使用条件变量的 wait 方法可以避免忙等,提高效率。
立即学习“C++免费学习笔记(深入)”;
下面是一个简单的生产者-消费者示例,展示如何使用上面的阻塞队列:
#include <iostream>
void producer(BlockingQueue<int>& queue) {
for (int i = 0; i < 5; ++i) {
queue.put(i);
std::cout << "Produced: " << i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void consumer(BlockingQueue<int>& queue) {
for (int i = 0; i < 5; ++i) {
int value;
queue.take(value);
std::cout << "Consumed: " << value << "\n";
}
}
int main() {
BlockingQueue<int> queue(3); // 容量为3的队列
std::thread p(producer, std::ref(queue));
std::thread c(consumer, std::ref(queue));
p.join();
c.join();
return 0;
}
在这个例子中,生产者每100毫秒放入一个数字,消费者取出并打印。由于队列容量有限,生产者在队列满时会自动阻塞,直到消费者取走元素。
实际使用中还需注意以下几点:
基本上就这些。一个简洁、可靠的阻塞队列能大大简化多线程程序的设计,是并发编程中的基础工具之一。
以上就是C++如何实现一个阻塞队列_C++多线程编程与阻塞队列实现的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号