Matej Briškár
Matej Briškár

Reputation: 607

How is mutex internally implemented

I've spent some time trying to understand how are mutexes implemented in several languages. There are multiple links describing the topic (*) but if I understand that correctly, all that hardware provides are some atomic operations that may help to distinguish who should be in turn now.

In software this is always used for busy waiting (try CAS or test-and-set and wait in while cycle if not successful), but how does the scheduler know that now I should take away the process/thread from CPU because all it does is that it waits? Is there some support in OS provided that for example Java synchronization uses in order to signal that "I am blocked, please let other Threads run instead"? I think it is, since busy-waiting is an alternative to use lock(); (so they should not be the same)

*Source:

Upvotes: 4

Views: 5423

Answers (2)

Victor Sorokin
Victor Sorokin

Reputation: 12006

In Linux JDK soure C code uses pthread library which is part of standard C library. That, in turn, uses Linux kernel futex feature (man futex). As far as I can understand, this implemented using kernel scheduler to put calling thread to sleep and to wake it back when signal received.

Scheduler itself relies on timer interrupts (hardware) to work -- essentially, everytime timer interrupt arrives, scheduler has to check if current user-space thread wants/must be suspended and, if yes, it must choose some other thread.

Here few further links for much more clear and detailed explanation:

  1. http://man7.org/linux/man-pages/man7/futex.7.html
  2. http://www.quora.com/How-different-is-a-futex-from-mutex-conceptually-and-also-implementation-wise
  3. Book by Robert Love's Linux Kernel Development (but, oddly enough, it does not contain a single mention of futex) and another book (which does contain futex mentions but mostly in references to external papers): Kerrisk's The Linux Programming Interface.

Upvotes: 5

Solomon Slow
Solomon Slow

Reputation: 27190

That's a book level topic. Here's the book:

The Art of Multiprocessor Programming Maurice Herlihy, Nir Shavit ISBN-13: 978-0123973375

https://www.amazon.com/Art-Multiprocessor-Programming-Revised-Reprint/dp/0123973376/


And actually, here's another because there's more to user-level mutexes as provided by an operating system than just using the hardware primitives. User-level mutexes are intimately tied to the operating system's scheduling algorithms.

Understanding the Linux Kernel Daniel P. Bovet, Marco Cesati ISBN-13: 978-0596005658

http://www.amazon.com/Understanding-Linux-Kernel-Third-Daniel/dp/0596005652/

Upvotes: 3

Related Questions