You don't have to prevent it, it is taken care of by the implementation of the standard library.
The cited code is for illustration purposes only: the behavior of lock()
is as this code, but atomically with regard to other threads.
If you want to know how it is done, you can peek the source code. It is a template class, so the code will surely be in the header files. But beware! The standard C++ library source code is not for the faint of heart.