Assuming, I have std::vector and two threads.
First thread is processing erase function while second thread is in for-loop
Is this situation a thread-safe?
Would second thread keep running or throwing an exception?
#include <iostream>
#include <vector>
#include <thread>
int main()
{
std::vector<int> intContainer;
for ( int index = 0; index <= 100000; ++index){
intContainer.push_back(index);
}
std::thread t1([&](){
while ( 1 ){
intContainer.erase( std::find(intContainer.begin(), intContainer.end(), random(1, 100000) ) );
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
std::thread t2([&] (){
for ( auto& val : intContainer ){
std::cout << val << std::endl;
}
});
t1.join();
t2.join();
return 0;
}