How it works...
The core idea is to order mutexes somehow and lock them always following that particular order. In that case, there's no ABBA problem possible, as all the threads would always lock mutex A before B. Usually, other deadlock avoidance algorithms are used but for the simplicity of the example here, we assume that the ordering of mutexes is used.
In the first example, we used boost::make_unique_locks that always locks threads in some particular order and returns a tuple that holds the locks.
In the second example, we created the locks manually but have not locked them thanks to a passed boost::defer_lock parameter. The actual locking happened in the boost::lock(l0, l1) call, which locked the mutexes in some predefined order.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access