- 2075 Bhadra · 4 marks
Mutual exclusion via sleep and wake
Short answer
Sleep/wake mutual exclusion puts a task to sleep when a resource is locked, queuing it, and wakes it upon release, eliminating CPU waste. The sleep-and-test must be atomic to avoid lost wake-ups.
In RTOS, describe mutual exclusion through sleep and wake for task synchronization.
Mutual exclusion means that only one task at a time may execute its critical section (code using a shared resource). Busy waiting does this by spinning and wasting CPU. Sleep and wake solves this by putting the waiting task to sleep (blocked state) so it uses no CPU, and waking it when the resource becomes free.
Operation
- A task wants to enter the critical section and finds the resource locked by another task.
- Instead of looping, it calls sleep() (block): the kernel moves it to the blocked state, adds it to the resource's wait queue and runs another ready task.
- When the owner finishes the critical section and releases the resource, it calls wakeup() for the waiting task.
- The kernel moves the woken task to the ready state; when scheduled, it enters the critical section.
void enter(void) /* acquire */
{
disable_interrupts();
if (locked) { add_to_wait_queue(me); sleep(); }
else locked = 1;
enable_interrupts();
}
void leave(void) /* release */
{
disable_interrupts();
if (queue_not_empty()) wakeup(remove_from_queue());
else locked = 0;
enable_interrupts();
}
Semaphores and mutexes are the standard implementations of sleep/wake.
Advantages: no CPU wasted, fair order through the queue, suits long waits. Problem to avoid: lost wake-up (a wakeup sent before the task goes to sleep is lost), solved by testing and sleeping atomically, as semaphores do. Also priority inversion and deadlock must be considered.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Task synchronization using busy/wait · Embedded System, chapter 6
- Synchronization issues in RTOS · Embedded System, chapter 6 · asked 2×
- Ricart-Agrawala mutual exclusion · Distributed System, chapter 6 · asked 2×
- Token ring mutual exclusion · Distributed System, chapter 6 · asked 3×
- Lamport algorithm for mutual exclusion · Distributed System, chapter 6
- Critical section; mutual exclusion · Operating System, chapter 3