如何保护向量v免遭崩溃?还有一个问题,为什么它不是已经崩溃了,不是吗?通过多线程访问矢量?
#include <Windows.h>
#include <thread>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> v;
void a()
{
while (true)
{
v.push_back(1);
Sleep(100);
}
}
void b()
{
while (true)
{
if (!v.empty())
{
v.erase(v.begin());
}
Sleep(100);
}
}
void c()
{
while (true)
{
v.push_back(1);
Sleep(100);
}
}
int main()
{
thread(&a).detach();
thread(&b).detach();
thread(&c).detach();
while (true)
{
for (int i = 0; i < v.size(); i++)
{
v[i]++;
}
cout << v.size() << endl;
if (!v.empty())
v.erase(v.begin());
Sleep(100);
}
}
A [mutex](http://en.cppreference.com/w/cpp/thread/mutex)? –
可能的重复:http://stackoverflow.com/questions/12260946/c-access-to-vector-from-multiple-threads – Default
只是添加到别人说的话,如果你只是从多个线程读取矢量的内容,它是线程安全的。 – NeonGlow