std::lock_guard example, explanation on why it works

Let’s have a look at the relevant line:

std::lock_guard<std::mutex> guard(myMutex);

Notice that the lock_guard references the global mutex myMutex. That is, the same mutex for all three threads. What lock_guard does is essentially this:

  • Upon construction, it locks myMutex and keeps a reference to it.
  • Upon destruction (i.e. when the guard’s scope is left), it unlocks myMutex.

The mutex is always the same one, it has nothing to do with the scope. The point of lock_guard is just to make locking and unlocking the mutex easier for you. For example, if you manually lock/unlock, but your function throws an exception somewhere in the middle, it will never reach the unlock statement. So, doing it the manual way you have to make sure that the mutex is always unlocked. On the other hand, the lock_guard object gets destroyed automatically whenever the function is exited – regardless how it is exited.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)