Guide
basic
ownership
- shared ownership
- exclusive ownership
- upgrade ownership—>exclusive ownership
mutex
- boost::mutex enable exclusive access to shared data.
- boost::shared_mutex enable shared access to shared data.
lock
- boost::shared_lock
- boost::unique_lock
- boost::upgrade_lock
- boost::upgrade_to_unique_lock
Tips from difference-between-boostunique-lock-and-boostupgrade-lock
The difference between
upgrade_lock
andunique_lock
is simple. An instance ofunique_lock
is acquiring a full exclusive ownership of ashared_mutex
. This means that no one else can get any type of ownership while theunique_lock
is alive.
Unlike the
unique_lock
an instance ofupgrade_lock
is acquiring an upgrade ownership that exclusive only amongst threads trying to get the same upgrade ownership. All other threads that try to get a shared ownership could acquire it with no conflict until theupgrade_lock
is upgraded to unique (with an instance ofupgrade_to_unique_lock
).
The
upgrade_lock
is useful when some of threads can be readers only and will not try to promote itself to writers. Otherwise (all readers may try to become writers at some point)upgrade_lock
will operate asunique_lock
.
conclusions
thread-A get
shared_lock
,other threads cannot getunique_lock,upgrade_lock
,but can getshared_lock
.(multiple-reader)thread-A get
upgrade_lock
,other threads cannot getunique_lock,upgrade_lock
,but can getshared_lock
.upgrade_lock
can upgrade toupgrade_to_unique_lock
,it’s same as thread-A getunique_lock
.thread-A get
unique_lock
,other threads cannot getunique_lock,upgrade_lock,shared_lock
. (single-writer)
code example
1 |
|
Reference
- synchronization
-example-for-boost-shared-mutex-multiple-reads-one-write - difference-between-boostunique-lock-and-boostupgrade-lock
History
- 20180523 created.