I see he used a mutex. You have to be a bit careful with these because only one thread can hold a mutex at once (until the unlock method is called). Other threads have to wait until it's released.
If you're doing something that takes a long time, that might be painful.
https://en.wikipedia.org/wiki/Test-and-set The mutex is likely implemented with some sort of atomic instruction like this.