The task of a mutex is to protect the object from access to it by other threads than the one that took possession of the mutex. At any given moment, only one thread can own an object protected by a mutex. If another thread needs access to a variable protected by a mutex, then that thread will block until the mutex is released.
But how does a mutex determine which resource/object/variable to block? After all, no parameters are passed to it, from which it could know what to protect.
If anything, it's about
std::mutex , c++11 .
I'll add to @alexis031182's answer.
A mutex or semaphore, as its generalization (specifically, an object (variable) located at some address) is a synchronization point for the code flows of one or (in some cases) several processes.
And nothing more. It doesn't protect anything. Neither objects in memory, nor sections of code. A thread that does not call a
lock operation with this mutex can do whatever it wants with any variables and code sections. Protection is performed at the logical level (in the developer's head).
In fact, the code thread that called the
lock operation on the specified mutex increments the counter associated with that mutex and continues execution if the counter was zero.
Otherwise, this thread waits until the counter is 0 (when it increments it in turn and continues running), which will happen when someone calls
unlock , which decrements the counter by 1.