A semaphore is a blocking synchronisation primitive. Describe how they work with the
aid of pseudo-code. You can assume the existance of a thread_block() and a thread_wakeup()
function
Answer:
-Semaphores work by blocking processes with P, calling thread_block(), waiting for a resource if it is not available, then being put into a queue of processes that want to access this resource. This is more efficient than other solutions because we avoid busy waiting – other processes can do other things while blocked ones are in the queue! When a resource is released, V is run, which calls thread_wakeup() to
signal the next thread to use it. See:
typedef struct _semaphore {
int count;
struct process *queue;
} semaphore;
semaphore sem;
void P(sem) {
sem.count--;
if (sem.count < 0) {
/* add process to sem.queue */
thread_block();
}
}
void V(sem) {
sem.count++;
if (sem.count <= 0) {
/* remove a process from sem.queue */
thread_wakeup();
}
}