3

默认情况下, 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;
}

我越来越:

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

我在这里做错了什么?

编辑

显然我误读了上面的链接。是否有可用的线程安全队列实现来做我想做的事情?我知道这是一种常见的线程组织策略。

4

3 回答 3

5

正如评论中所指出的,STL 容器对于读写操作不是线程安全的。相反,尝试concurrent_queueTBBPPL类,例如:

void doWork(concurrent_queue<string>& itemQueue) {
    string result;
    while(itemQueue.try_pop(result)) {
        // you have `result`
    }   
}
于 2014-05-14T01:11:07.600 回答
2

我最终在此处实施了BlockingQueue,并建议修复pop

创建阻塞队列

于 2014-05-14T18:24:31.617 回答
0

C++ 容器绝对不是线程安全的。BlockingCollection是一个 C++11 线程安全集合类,它以 .NET BlockingCollection 类为模型。它包装 std::deque 以提供从多个线程到队列的并发添加和获取项目。以及堆栈和优先级容器。

于 2018-10-08T11:04:55.080 回答