如何进行多线程队列处理
How to multithread queue processing
c++容器默认是线程安全的。我必须使用queue
多线程不正确,因为这段代码:
#include <thread>
using std::thread;
#include <iostream>
using std::cout;
using std::endl;
#include <queue>
using std::queue;
#include <string>
using std::string;
using std::to_string;
#include <functional>
using std::ref;
void fillWorkQueue(queue<string>& itemQueue) {
int size = 40000;
for(int i = 0; i < size; i++)
itemQueue.push(to_string(i));
}
void doWork(queue<string>& itemQueue) {
while(!itemQueue.empty()) {
itemQueue.pop();
}
}
void singleThreaded() {
queue<string> itemQueue;
fillWorkQueue(itemQueue);
doWork(itemQueue);
cout << "donen";
}
void multiThreaded() {
queue<string> itemQueue;
fillWorkQueue(itemQueue);
thread t1(doWork, ref(itemQueue));
thread t2(doWork, ref(itemQueue));
t1.join();
t2.join();
cout << "donen";
}
int main() {
cout << endl;
// Single Threaded
cout << "singleThreadedn";
singleThreaded();
cout << endl;
// Multi Threaded
cout << "multiThreadedn";
multiThreaded();
cout << endl;
}
我:
singleThreaded
done
multiThreaded
main(32429,0x10e530000) malloc: *** error for object 0x7fe4e3883e00: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
make: *** [run] Abort trap: 6
我在这里做错了什么?
编辑
显然我读错了上面的链接。是否有一个线程安全的队列实现可以做我想做的事情?我知道这是一个常见的线程组织策略正如注释所指出的,对于读写操作,STL容器不是线程安全的。相反,尝试从TBB或PPL的concurrent_queue
类,例如:
void doWork(concurrent_queue<string>& itemQueue) {
string result;
while(itemQueue.try_pop(result)) {
// you have `result`
}
}
我最终实现了BlockingQueue
,并建议修复pop
,在这里:
创建阻塞队列
c++容器绝对不是线程安全的。BlockingCollection是一个c++ 11线程安全的集合类,以。net BlockingCollection类为模型。它包装了std::deque,以提供从多个线程并发添加和获取项目到队列的功能。以及堆栈和优先级容器
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 有关如何处理 vulkan 队列系列的问题
- asio::io_service 具有多个线程的优先级队列处理
- C++11如何在1个线程中使用条件变量处理2个线程安全队列
- 为什么事件队列未处理我的QT信号
- Qt的事件循环线程是安全的还是原子的?处理"队列连接"时如何同步?
- 接收不一致的访问冲突,处理队列
- 用管道在C++中创建调度队列/线程处理程序:FIFO溢出
- 如何处理多个源队列消息类型
- 为什么在使用队列处理扫雷中的相邻单元格时会出现无限循环?
- 在控制台应用程序中处理空的windows消息队列
- win32消息泵,do dispatchMessage()处理整个消息队列或仅仅是顶部消息
- 未定义的引用C++队列模板处理字符串
- 将队列处理为包含文件的文件夹.可能存在的问题
- 如何处理队列前端和 POP 功能
- 如何处理不同大小的 Linux 消息队列(POSIX 或 SysV)中的信号
- c++处理队列溢出
- 正在处理由双链接列表组成的学生队列
- 如何进行多线程队列处理