Is there any idiomatic explicit use of mutex::lock() or unlock()?

折月煮酒 提交于 2019-12-05 16:11:30

lock_guard isn't the only thing that needs to call lock/unlock on a mutex. unique_lock, lock, try_lock and condition_variable_any all have to work on mutexes as well. And that is just the standard types. Friendship in this case introduces a tight coupling that becomes a hinderance.

RAII can be (and should be) used when there is a static scope to which the lifetime of a resource can be bound, i.e. the resource should be initialized when the scope is entered and freed when the scope is exited.

There are situations, however, when there is no such static scope. To illustrate this, consider variables as resources. We use automatic variables when there is a static scope to which we can bound them, but occasionally we need dynamic variables to control when they are created and destroyed.

The same can happen when we use mutexes for mutual exclusion. Consider this task:

Your program controls two resources, it has to read and execute a sequence of commands. Possible commands are:

  • lock resource #1 : 1>
  • lock resource #2 : 2>
  • unlock resource #1 : 1<
  • unlock resource #2 : 2<
  • write x to resource #1 : 1x
  • write x to resource #2 : 2x

your program can expect inputs like 1> 1a 2> 2b 1c 1< 2d 2<, which makes the use of static scopes for RAII impossible if the program obeys the commands (the scopes would have to overlap partially). So I think this illustrates one situation when explicit lock/unlock is necessary.


There is at least one other possible scenario which comes from the fact that mutual exclusion is not the only situation when one could use a mutex: it can be used for synchronisation as well.

Consider two parallel processes, P and Q, each with a designated point in their code. We require that Q cannot pass its designated point until P reaches its own. This requirement can be met by using a mutex initialised to locked state and placing a lock() operation right before the designated point of Q and an unlock() right after the designated point of P. It can be easily verified that this setup solves the problem.

Here lock() is placed in one process and unlock() in another, again there is obviously no static scope that can enclose them, so we need both to be accessible independently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!