c++ - 如何多线程队列处理

标签 c++ multithreading c++11 concurrent-queue

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/

相关文章:

c++ - 删除指针和将其设置为 nullptr 之间有什么区别?

c++ - 如何检测丢失的字体字符

c++ - 如何根据输入从数组中检索元素?

c - C语言中的素数

c++ - 按值或右值引用传递

c++ - 为什么我默认的移动构造函数不是 noexcept?

c++ - SWIG 不扩展嵌套宏 "Error: Syntax error in input(3)"

c# - 需要帮助使用线程来监视指定文件夹中的 txt 文件

java - 在与主线程不同的另一个线程中启动 swing gui,以在计算时更新 jtextarea

c++ - mingw 4.7.1 上的 stoi 和 std::to_string