Mutex Types and Locking Methods

This lesson discusses different types of mutexes and their locking methods

C++ has five different mutexes that can lock recursively (i.e., multiple layers of locking), tentative with and without time constraints.

Method mutex recursive_mutex timed_mutex recursive_timed_mutex shared_timed_mutex
m.lock yes yes yes yes yes
m.unlock yes yes yes yes yes
m.try_lock yes yes yes yes yes
m.try_lock_for no no yes yes yes
m.try_lock_until no no yes yes yes
m.try_lock_shared yes no no no yes
m.try_lock_shared_for no no no no yes
m.try_lock_shared_until no no no no yes


With C++14 we have an std::shared_timed_mutex that is the base for reader-writer locks. It solves the infamous reader-writer problem.

The std::shared_timed_mutex enables you to implement reader-writer locks which means that you can use it for exclusive or shared locking. You will get an exclusive lock if you put the std::shared_timed_mutex into a std::lock_guard; you will get a shared lock if you put it into an std::shared_lock.

std::shared_mutex with C++17

With C++17 we get a new mutex: std::shared_mutex. std::shared_mutex is similar to std::shared_timed_mutex. Like the std::shared_timed_mutex, you can use it for exclusive or shared locking, but you can not specify a time point or a time duration.

Mutex try_lock methods

The m.try_lock_for(relTime) (m.try_lock_shared_for(relTime)) method needs a relative time duration; the m.try_lock_until(absTime) (m.try_lock_shared_until(absTime)) method needs an absolute time point.

m.try_lock (m.try_lock_shared) tries to lock the mutex and returns immediately. On success, it returns true; otherwise, it’s false. In contrast, the methods try_lock_for (try_lock_shared_for) and try_lock_until (try_lock_shared_until) try to lock until the specified timeout occurs or the lock is acquired, whichever comes first. You should use a steady clock for your time constraint. A steady clock cannot be adjusted.

Tip: You should not use mutexes directly; you should put mutexes into locks.

Get hands-on with 1000+ tech skills courses.