어떻게하면 벡터 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);
}
}
[mutex] (http://en.cppreference.com/w/cpp/thread/mutex)? –
가능한 복제본 : http://stackoverflow.com/questions/12260946/c-access-to-vector-from-multiple-threads – Default
다른 사람들이 말한 것을 추가하기 만하면 여러 스레드에서 벡터 내용을 읽는 경우 , 스레드로부터 안전합니다. – NeonGlow