C ++容器是supposed to be thread-safe by default。我必须使用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 << "done\n";
}
void multiThreaded() {
queue<string> itemQueue;
fillWorkQueue(itemQueue);
thread t1(doWork, ref(itemQueue));
thread t2(doWork, ref(itemQueue));
t1.join();
t2.join();
cout << "done\n";
}
int main() {
cout << endl;
// Single Threaded
cout << "singleThreaded\n";
singleThreaded();
cout << endl;
// Multi Threaded
cout << "multiThreaded\n";
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
我在这里做错了什么?
修改
显然我误读了上面的链接。是否有可用的线程安全队列实现,我正在尝试做什么?我知道这是一个共同的线程组织策略。
答案 0 :(得分:4)
正如注释中所指出的,STL容器对于读写操作不是线程安全的。相反,请尝试TBB或PPL中的concurrent_queue
类,例如:
void doWork(concurrent_queue<string>& itemQueue) {
string result;
while(itemQueue.try_pop(result)) {
// you have `result`
}
}
答案 1 :(得分:2)
我最终实施了一个BlockingQueue
,其中包含对pop
的建议修正,此处:
答案 2 :(得分:0)
C ++容器绝对不是线程安全的。 BlockingCollection是一个C ++ 11线程安全集合类,它以.NET BlockingCollection类为模型。它包装std :: deque以提供从多个线程到队列的并发添加和接收项。以及堆栈和优先级容器。