Chr*_*ord 6 c++ multithreading c++11 concurrent-queue
默认情况下,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 << "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;
}
Run Code Online (Sandbox Code Playgroud)
我越来越:
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
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
编辑
显然我误读了上面的链接。是否有可用的线程安全队列实现来完成我想要做的事情?我知道这是一个常见的线程组织策略。
正如评论中指出的,STL 容器对于读写操作不是线程安全的。相反,尝试TBB或PPLconcurrent_queue中的类,例如:
void doWork(concurrent_queue<string>& itemQueue) {
string result;
while(itemQueue.try_pop(result)) {
// you have `result`
}
}
Run Code Online (Sandbox Code Playgroud)