thread scheduling at mutex unlock

David Schwartz davids at webmaster.com
Thu May 15 22:37:43 UTC 2008


> David,
 
> thank you for the tutorial, it is quite enlightening.
> But first of all, did you take a look at my small test program?

Yes. It demonstrates the classic example of mutex abuse. A mutex is not an appropriate synchronization mechanism when it's going to be held most of the time and released briefly.

> There are 1 second sleeps in it, this is not about timeslices and 
> scheduling at that level at all. This is about basic expectation about 
> fairness of acquiring a lock at macro level. I know that when one thread 
> acquires and releases and reacquires a mutex during 10 seconds while the 
> other thread is blocked on that mutex for 10 seconds, then this is not 
> about timeslices.

I guess it comes down to what your test program is supposed to test. Threading primitives can always be made to look bad in toy test programs that don't even remotely reflect real-world use cases. No sane person optimizes for such toys.

The reason your program behaves the way it does is because the thread that holds the mutex relinquishes the CPU while it holds it. As such, it appears to be very nice and is its dynamic priority level rises. In a real-world case, the threads waiting for the mutex will have their priorities rise while the thread holding the mutex will use up its timeslice working.

This is simply not appropriate use of a mutex. It would be absolute foolishness to encumber the platform's default mutex implementation with any attempt to make such abuses do more what you happen to expect them to do.

In fact, the behavior I expect is the behavior seen. So the defect is in your unreasonable expectations. The scheduler's goal is to allow the running thread to make forward progress, and it does this perfectly.

DS




More information about the freebsd-threads mailing list