Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are mutexes implemented?

Are some implementations better than others for specific applications? Is there anything to earn by rolling out your own?

like image 439
static_rtti Avatar asked Sep 28 '09 08:09

static_rtti


People also ask

How are locks implemented?

Locks have two operations: acquire allows a thread to take ownership of a lock. If a thread tries to acquire a lock currently owned by another thread, it blocks until the other thread releases the lock. At that point, it will contend with any other threads that are trying to acquire the lock.

How is the locking system implemented in mutex?

Mutex lock will only be released by the thread who locked it. So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.

How do mutexes work?

The idea behind mutexes is to only allow one thread access to a section of memory at any one time. If one thread locks the mutex, any other lock attempts will block until the first one unlocks.


2 Answers

Check out the description of the Test-and-set machine instruction on Wikipedia, which alludes to how atomic operations are achieved at the machine level. I can imagine most language-level mutex implementations rely on machine-level support such as Test-and-set.

like image 149
Adamski Avatar answered Sep 27 '22 22:09

Adamski


Building on Adamski's test-and-set suggestion, you should also look at the concept of "fast user-space mutexes" or futexes.

Futexes have the desirable property that they do not require a kernel system call in the common cases of locking or unlocking an uncontended mutex. In these cases, the user-mode code successfully uses an atomic compare and swap (CAS) operation to lock or unlock the mutex.

If CAS fails, the mutex is contended and a kernel system call -- sys_futex under Linux -- must be used either to wait for the mutex (in the lock case) or to wake other threads (in the unlock case).

If you're serious about implementing this yourself, make sure you also read Ulrich Drepper's paper.

like image 44
David Joyner Avatar answered Sep 27 '22 22:09

David Joyner