Arguments of Threads: Race Conditions and Locks

This lesson defines race conditions, and explains how to address them in concurrent programming with C++.

Both issues from the previous lesson are actually race conditions because the result of the program depends on interleaving the operations. The race condition is the cause of the data race.

Fixing the data race is quite easy; valSleeper should be protected using either a lock or an atomic. To overcome the lifetime issues of valSleeper and std::cout, we have to join the thread instead of detaching it.

Here is the modified main function:

Get hands-on with 1200+ tech skills courses.