1

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?

1 Answers1

1

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().

sehe
  • 374,641
  • 47
  • 450
  • 633
  • sehe, the boost master to the rescue as usual! In my case, I'm only using a `boost::unique_lock` and `boost::mutex` in multiple threads. Do you happen to know if with that simple example the order of calls to `unique_lock` is preserved? Thank you so much in advance sehe! –  Jul 13 '14 at 23:25
  • You need to look into the pthreads/Win32 documentation. I've tried to find compelling reasons why it cannot be anything else, but haven't thought of a pressing reason (_e.g. I don't think that arbitrarily changing the thread priorities will introduce potential for deadlock as long as the locks are acquired in consistent order_). Of course, if you want to design systems that respond predictably (prevent starvation/worst-case behaviour like soft-lock) under heavy load you would _want_ to refer to your platform's documentation for confirmation about it's scheduling priorities. – sehe Jul 14 '14 at 06:33
  • Thank you for the details sehe! I'm all linux and still too inexperienced to get that deep, so I think I might try to fight through maintaining multiple lock order to prevent deadlocks instead of assuming that a lock might do this or that. Thank you so much for sharing your amazing knowledge, again and again!!! –  Jul 14 '14 at 06:37