Search code examples
boostlockingqueueboost-mutexcontention

Are boost::unique_locks granted in the order that they are called?


I've examined the documentation on Boost Synchronization, and I cannot seem to determine if a boost::unique_lock will attain its lock in order.

In other words, if two threads are contending to lock a mutex which is already locked, will the order that they attempt to lock be maintained after the lock is released?


Solution

  • Unique lock is not a lock (it's a lock adaptor that can act on any Lockable or TimedLockable type, see cppreference).

    The order in which threads get the lock (or resources in general) is likely implementation defined. These implementations usually have well-documented scheduling semantics, so applications can avoid resource starvation, soft-locks and dead locks.

    As an interesting example, condition variables preserve scheduling order only if you take care to signal them under the mutex (if you don't, things will usually work unless your scheduling crucially depends on fair scheduling):

    man phtread_cond_signal

    The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().