C++ STL queue 多线程报错:dereferencable

新手上路,请多包涵

如下,主线程循环调用 push() ,第二个线程 front() 读队首,队空时忙等,结果第11行 front() 处报错 deque iterator not dereferencable,看了一下 STL deque 的实现,感觉这两个操作不应该冲突啊?

#include "stdafx.h"

using namespace std;

queue<int>Q;
bool going = true;

void thread1() {
    while (going || !Q.empty()) {
        while (!Q.empty()) {
            int x = Q.front(); Q.pop();
        }
    }
}

int main()
{
    thread th(thread1);
    for (int i = 1; i <= 10000; i++)
        Q.push(i);
    going = false;
    th.join();
    return 0;
}
阅读 3.6k
1 个回答

stl里的容器都不是线程安全的,使用的时候注意加锁

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题