std::mutex
suggest changestd::mutex protects data accessed by multiple threads. The sample does not do that. temp is an std::atomic_int, so the individual atomic operations are not a data race, but the mutex is not held for every access: try_to_lock can fail and the increment still runs. Neither loop sets temp to -1 or otherwise stops, so the program does not terminate.
std::atomic_int temp{0};
std::mutex _mutex;
std::thread t( [&](){
while( temp!= -1){
std::this_thread::sleep_for(std::chrono::seconds(5));
std::unique_lock<std::mutex> lock( _mutex);
temp=0;
}
});
while ( true )
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::unique_lock<std::mutex> lock( _mutex, std::try_to_lock);
if ( temp < INT_MAX )
temp++;
cout << temp << endl;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents