Module mutex

Module mutex 

Source
Expand description

§Mutex.

Mutex is a synchronization primitive that allows only one thread at a time to access a critical section of code, protecting shared resources such as memory, files, or device state from concurrent modification. Unlike the spin lock, it blocks threads trying to acquire it if another thread already holds the lock.

The Mutex maintains the list of threads sleeping on the mutex. When unlocking, the kernel wakes up one of the waiting threads. In KeOS, you can sleep the current thread by calling the Current::park_with. This function takes a closure to run before falling in sleep with a argument ParkHandle, which is the handle to wake up the sleeping thread.

Although mutex and spin lock provides similar synchronization guarantees, they are used in different circumstances. The following table compares the spin lock and mutex.

SpinLockMutex
Waiting threadSpins (busy-waits)Sleeps
CPU usageHigh (wastes CPU cycles)Low (no busy waiting)
OverheadLow (fast if uncontended)Higher (due to sleep/wake)

These characterists lead that the spin lock is suitable when critical sections are extremely short and contention is rare, because spinning wastes CPU cycles. On the other side, the mutex is better for longer critical sections or when a lock may be held for a non-trivial amount of time, as sleeping threads do not waste CPU.

§Implementation Requirements

You need to implement the followings:

After implement the functionalities, move on to the next section.

Structs§

Mutex
A mutual exclusion primitive useful for protecting shared data
MutexGuard
An implementation of a “scoped lock” of a mutex. When this structure is dropped (falls out of scope) without unlocking, the panic occurs.