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
我在这里做错了什么?
编辑
显然我误读了上面的链接。是否有可用的线程安全队列实现来执行我正在尝试执行的操作?我知道这是一种常见的线程组织策略。
最佳答案
正如评论中所指出的,STL 容器对于读写操作不是线程安全的。相反,尝试使用 TBB 中的 concurrent_queue
类或 PPL ,例如:
void doWork(concurrent_queue<string>& itemQueue) {
string result;
while(itemQueue.try_pop(result)) {
// you have `result`
}
}
关于c++ - 如何多线程队列处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23643341/