如何进行多线程队列处理

How to multithread queue processing

本文关键字:处理 队列 多线程 何进行      更新时间:2023-10-16

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 << "donen";
}
void multiThreaded() {
    queue<string> itemQueue;
    fillWorkQueue(itemQueue);
    thread t1(doWork, ref(itemQueue));
    thread t2(doWork, ref(itemQueue));
    t1.join();
    t2.join();
    cout << "donen";
}
int main() {
    cout << endl;
    // Single Threaded
    cout << "singleThreadedn";
    singleThreaded();
    cout << endl;
    // Multi Threaded
    cout << "multiThreadedn";
    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或PPL的concurrent_queue类,例如:

void doWork(concurrent_queue<string>& itemQueue) {
    string result;
    while(itemQueue.try_pop(result)) {
        // you have `result`
    }   
}

我最终实现了BlockingQueue,并建议修复pop,在这里:

创建阻塞队列

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