相关疑难解决方法(0)

我从空std容器的front()得到什么?

如果front()返回一个引用并且容器是空的,我得到一个未定义的引用?这是否意味着我需要empty()在每个之前检查front()

c++ stl

47
推荐指数
3
解决办法
2万
查看次数

如何进行多线程队列处理

默认情况下,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)); …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading c++11 concurrent-queue

6
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×2

c++11 ×1

concurrent-queue ×1

multithreading ×1

stl ×1