I'm implementing some synchronization primitives in the standard library of an operating system. Specifically, I want to implement mutexes and condition variables. This is on top of a microkernel with a preemptive scheduler (a thread has no way to prevent the scheduler from preempting it). I'm exploring how minimalistic the system can get while remaining powerful and efficient enough for my needs. Compared with Mutex implementation on top of a minimalistic preemptive scheduler, there's a twist: the kernel does not guarantee thread liveness.
From the hardware, I get a basic atomic primitive such as compare-and-swap or load-link/store-conditional. You can assume that the word size for these instructions is large enough to store a pointer or a thread identifier.
From the kernel, I get two primitives:
sleep(): suspend the current thread until a thread has calledwake(t)wheretis the current thread. If the current thread's wake-up flag is already set thensleep()returns immediately. Returning fromsleepclears the wake-up flag.wake(t): wake threadtif it's asleep. Iftisn't asleep then its wake-up flag is set andt's next call tosleepwill return immediately.
Can I implement a mutex on top of these primitives?
lock(m): ifmis taken, sleep until it is free. Markmas taken.unlock(m): markmas free. If some other thread is waiting for it to become free, that thread is woken up.
Note the absence of a yield() primitive. If a thread does not go to sleep then there is no guarantee that some other thread will get any CPU time. Why? Because the scheduler assigns priorities to threads, and a low-priority thread will never run if all cores are busy running higher-priority threads. But the mutex functions must work between threads with different priorities.
If these primitives aren't enough to implement a locking mechanism, what feature can I add to the kernel to make it possible (keeping in mind that I'm trying to keep it small)? Note that I want to maintain the guarantee that high-priority threads won't be interrupted by low-priority thread if they don't take some explicit action permitting it.