I have a below code that gives segmentation fault sometime?
vector<int> myvector;
void function1()
{
for(int i = 0;i<10;i++)
{
cout<<"writer thread:"<<i<<endl;
myvector.push_back(i);
}
}
void function2()
{
for(int i = 0;i<10;i++)
{
cout<<"reader thread:";
cout<<myvector[i]<<endl;
}
}
int main()
{
thread t1(function1);
thread t2(function2);
t1.join();
t2.join();
}
I am little confused with the thread safe rules/guarantees on containers in general and vectors in particular. I was asked this question in an interview and failed to put in words why it write in on thread and write in other thread is not thread-safe operation.
in the below link for push_back of vectors I see "Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe" under Data Race section. How does this statement justify that vector write operation is not thread-safe?