This program will crash cause the threads are tangled... One could be pushing while the other is trying to erase.
How can I make this work?
#include <thread>
#include <vector>
using namespace std;
vector<int> v_test;
void push()
{
v_test.push_back(0);
}
void erase()
{
if (v_test.size() > 0)
{
v_test.erase(v_test.begin());
}
}
int main()
{
thread w0(push);
thread w1(erase);
while (true) { Sleep(1000); }
return 0;
}
CodePudding user response:
You need to synchronize the threads so they coordinate their access to the vector. For example, by using a std::mutex
, eg:
#include <thread>
#include <mutex>
#include <vector>
using namespace std;
vector<int> v_test;
mutex m_sync;
void push()
{
lock_guard<mutex> lock(m_sync);
v_test.push_back(0);
}
void erase()
{
lock_guard<mutex> lock(m_sync);
if (v_test.size() > 0)
{
v_test.erase(v_test.begin());
}
}
int main()
{
thread w0(push);
thread w1(erase);
while(true) {Sleep(1000);}
return 0;
}