如下,主线程循环调用 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;
}
stl里的容器都不是线程安全的,使用的时候注意加锁