在 C++ 中,queue 是一个先进先出的容器(FIFO:First In First Out),它基于逻辑结构“队列”进行实现,提供了按顺序存储数据的功能。它允许元素从队尾插入(push),从队首取出(pop)。通常用于数据的按顺序处理,比如任务调度、消息队列等。
C++ 标准库中的 queue 是通过适配器实现的,这意味着它不是一个独立的容器,而是依赖其他容器(如 deque 或 list)来实现底层的存储。
C++ queue 适配器的实现
C++ 标准库中的 queue 默认基于 deque 实现,也可以使用其他支持双端操作的容器,如 list。queue 适配器的主要操作依赖于底层容器来进行队尾插入和队首删除。
其典型实现如下:
- 队尾插入元素(push):通过调用底层容器的
push_back。 - 队首删除元素(pop):通过调用底层容器的
pop_front。
queue 的应用场景
- 任务调度:在多线程或并发编程中,
queue可以用于任务或作业的调度。多个生产者可以将任务加入队列,而多个消费者可以从队列中取出任务并执行。 - 消息队列:在分布式系统中,
queue常被用于消息传递,确保消息按顺序处理。 - 广度优先搜索(BFS):在图或树的广度优先搜索算法中,
queue是一种天然适用的数据结构,帮助按层次遍历节点。 - 数据流处理:用于需要按顺序处理数据流的应用场景,比如数据分析、流式处理等。
queue 常用操作及示例
#include <iostream>
#include <queue>
int main() {
std::queue<int> q; // 定义一个整型队列
// 插入元素
q.push(10); // 队尾插入10
q.push(20); // 队尾插入20
q.push(30); // 队尾插入30
// 访问队首元素
std::cout << "队首元素: " << q.front() << std::endl; // 输出10
// 访问队尾元素
std::cout << "队尾元素: " << q.back() << std::endl; // 输出30
// 删除队首元素
q.pop(); // 移除队首元素10
std::cout << "移除后队首元素: " << q.front() << std::endl; // 输出20
// 判断队列是否为空
if (!q.empty()) {
std::cout << "队列不为空" << std::endl;
}
// 队列的大小
std::cout << "队列大小: " << q.size() << std::endl; // 输出2
return 0;
}
常见坑和注意事项
-
pop()不返回值: 在使用pop()操作时,许多初学者会以为它会返回被移除的元素。实际上,pop()只是删除队首元素,因此如果你想使用队首元素,必须先用front()或back()访问。错误示例:
std::queue<int> q; q.push(10); int value = q.pop(); // 错误,pop不返回值正确示例:
int value = q.front(); // 先访问队首元素 q.pop(); // 再删除队首元素 -
空队列操作: 在
queue上调用front()或back()之前,必须确保队列不为空。如果队列为空时调用这些操作,行为是未定义的,可能导致程序崩溃。错误示例:
std::queue<int> q; std::cout << q.front(); // 如果队列为空,将导致未定义行为正确示例:
if (!q.empty()) { std::cout << q.front(); } -
适配器的容器限制:
queue默认使用deque作为底层容器,但也可以使用list。但是,不能使用vector,因为vector只支持尾部插入和尾部删除,无法支持队首删除操作。错误示例:
std::queue<int, std::vector<int>> q; // 错误,vector不能用作底层容器 -
线程安全问题:
queue并不自带线程安全性。在多线程环境下,需要对队列操作进行同步控制,可以使用诸如互斥锁(std::mutex)来保护共享队列。 -
性能注意: 对于频繁进行队首删除操作的场景,选择
deque或list作为底层容器比vector更高效,因为vector在队首删除时需要移动所有元素,而deque和list支持常数时间的队首操作。 -
queue与deque的比较虽然
queue通常基于deque实现,但它限制了deque的功能。与deque相比,queue只允许在队首删除、在队尾插入,不允许直接访问中间元素或在队首插入、队尾删除。
如何使用 std::queue 和 std::mutex
示例:使用 std::queue 和 std::mutex 实现线程安全队列
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::queue<int> q; // 全局队列
std::mutex mtx; // 互斥锁,用于保护队列的操作
std::condition_variable cv; // 条件变量,用于通知消费者有新数据
bool finished = false; // 标志生产者是否完成任务
// 生产者函数
void producer(int id, int num_items) {
for (int i = 0; i < num_items; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 模拟生产延迟
std::lock_guard<std::mutex> lock(mtx); // 使用互斥锁保护队列操作
q.push(i);
std::cout << "Producer " << id << " produced item: " << i << std::endl;
cv.notify_one(); // 通知等待的消费者有新数据
}
}
// 打印队列中的元素
void printQueue() {
std::queue<int> tempQueue = q; // 使用临时队列,避免改变原队列
std::cout << "Current queue: [ ";
while (!tempQueue.empty()) {
std::cout << tempQueue.front() << " ";
tempQueue.pop();
}
std::cout << "]" << std::endl;
}
// 消费者函数
void consumer(int id) {
while (true) {
std::unique_lock<std::mutex> lock(mtx); // 获取互斥锁
cv.wait(lock, [] { return !q.empty() || finished; }); // 等待队列有数据或生产完成
if (!q.empty()) { // 使用 if 确保队列非空且只消费一个数据
std::cout << "before consuming, the queue is: ";
printQueue();
int item = q.front(); // 取出队列头部的数据
q.pop(); // 删除队列头部的数据
std::cout << "Consumer " << id << " consumed item: " << item << std::endl;
// 打印消费后的队列状态
std::cout << "After consuming, the queue is: ";
printQueue(); // 打印队列剩余状态
}
if (finished && q.empty()) {
break; // 如果生产已经完成且队列为空,退出循环
}
}
}
int main() {
const int num_producers = 2;
const int num_consumers = 3;
const int num_items_per_producer = 5;
std::thread producers[num_producers];
std::thread consumers[num_consumers];
// 启动生产者线程
for (int i = 0; i < num_producers; ++i) {
producers[i] = std::thread(producer, i, num_items_per_producer);
}
// 启动消费者线程
for (int i = 0; i < num_consumers; ++i) {
consumers[i] = std::thread(consumer, i);
}
// 等待所有生产者完成
for (int i = 0; i < num_producers; ++i) {
producers[i].join();
}
// 设置生产完成标志
{
std::lock_guard<std::mutex> lock(mtx);
finished = true;
}
cv.notify_all(); // 通知所有消费者生产已完成
// 等待所有消费者完成
for (int i = 0; i < num_consumers; ++i) {
consumers[i].join();
}
std::cout << "All tasks completed!" << std::endl;
return 0;
}
代码说明
-
该代码实现了生产者-消费者模型,其中多个生产者将数据放入共享队列,多个消费者从队列中消费数据。程序使用多线程来实现并行执行,结合互斥锁和条件变量来同步队列的访问,避免数据竞争。
-
全局变量:
std::queue<int> q: 共享的队列,用于存储生产者生成的整数项。std::mutex mtx: 互斥锁,保护对队列的并发访问,确保队列操作的原子性。std::condition_variable cv: 条件变量,用于在队列有新数据或生产结束时通知等待的消费者线程。bool finished: 标志变量,表示所有生产者是否已完成工作,用于通知消费者程序结束。
-
生产者函数 (
producer):- 该函数模拟生产者生成数据。每个生产者线程依次生成
num_items个整数,将其放入队列中,并通过cv.notify_one()通知消费者有新数据可以消费。每生产一个项目,生产者线程会休眠1秒,模拟生产延迟。
- 该函数模拟生产者生成数据。每个生产者线程依次生成
-
消费者函数 (
consumer):- 该函数负责消费队列中的数据。消费者线程会等待直到队列有数据或所有生产者完成任务。当队列非空时,消费者从队列头部取出数据并消费,然后打印队列状态。如果生产者已完成且队列为空,消费者线程将退出。
-
主函数 (
main):- 初始化2个生产者线程和3个消费者线程,生产者每人生成5个项目。
- 启动所有线程并等待生产者完成后,将
finished标志设置为true,并通过cv.notify_all()通知消费者可以停止等待。最后等待所有消费者完成任务,输出 "All tasks completed!"。
Producer 1 produced item: 0
Producer 0 produced item: 0
before consuming, the queue is: Current queue: [ 0 0 ]
Consumer 0 consumed item: 0
After consuming, the queue is: Current queue: [ 0 ]
before consuming, the queue is: Current queue: [ 0 ]
Consumer 0 consumed item: 0
After consuming, the queue is: Current queue: [ ]
Producer 0 produced item: 1
Producer 1 produced item: 1
before consuming, the queue is: Current queue: [ 1 1 ]
Consumer 2 consumed item: 1
After consuming, the queue is: Current queue: [ 1 ]
before consuming, the queue is: Current queue: [ 1 ]
Consumer 2 consumed item: 1
After consuming, the queue is: Current queue: [ ]
Producer 1 produced item: 2
Producer 0 produced item: 2
before consuming, the queue is: Current queue: [ 2 2 ]
Consumer 1 consumed item: 2
After consuming, the queue is: Current queue: [ 2 ]
before consuming, the queue is: Current queue: [ 2 ]
Consumer 1 consumed item: 2
After consuming, the queue is: Current queue: [ ]
Producer 0 produced item: 3
Producer 1 produced item: 3
before consuming, the queue is: Current queue: [ 3 3 ]
Consumer 0 consumed item: 3
After consuming, the queue is: Current queue: [ 3 ]
before consuming, the queue is: Current queue: [ 3 ]
Consumer 0 consumed item: 3
After consuming, the queue is: Current queue: [ ]
Producer 0 produced item: 4
Producer 1 produced item: 4
before consuming, the queue is: Current queue: [ 4 4 ]
Consumer 2 consumed item: 4
After consuming, the queue is: Current queue: [ 4 ]
before consuming, the queue is: Current queue: [ 4 ]
Consumer 2 consumed item: 4
After consuming, the queue is: Current queue: [ ]
All tasks completed!
注意事项
-
互斥锁的使用:
- 为了防止多个线程同时访问共享队列,使用
std::mutex保护对队列的访问。在生产者和消费者中,使用std::lock_guard或std::unique_lock来管理互斥锁,确保线程安全。
- 为了防止多个线程同时访问共享队列,使用
-
条件变量的使用:
std::condition_variable用于消费者线程的同步。生产者通过cv.notify_one()唤醒一个等待的消费者线程,而消费者在等待队列中有数据时被唤醒。
-
线程等待与唤醒:
- 在消费者函数中,
cv.wait(lock, [] { return !q.empty() || finished; });保证了消费者线程在队列为空时会等待,直到有新数据或所有生产者都完成任务。
- 在消费者函数中,
-
线程同步:
- 主线程需要等待所有生产者和消费者完成任务,分别通过
join()函数实现。生产者完成任务后,主线程设置finished为true,并使用cv.notify_all()唤醒所有等待的消费者。
- 主线程需要等待所有生产者和消费者完成任务,分别通过
-
防止重复消费:
- 代码通过互斥锁和条件变量确保同一时间只有一个消费者线程能访问队列,防止多个消费者重复消费同一个项目。
299




被折叠的 条评论
为什么被折叠?



