Semaphores
- Spinlocks let a process
continue to use the processor (wasting CPU) when waiting for a critical
region or resource to become available
- Semaphores release the
processor from the currently executing process, save the state of this
process, and call the dispatcher to scheduler another process on the
processor
- A semaphore can be used to
protect a critical region of code
Skeleton
Code for Binary Semaphore
- wait(sem): if sem = 1 then sem:= 0; else
place process in sem.queue;
- signal(sem): if sem.queue
not empty
then remove a process from the queue and place in ready list
else sem :=1;
- A binary semaphore allows just
one process in the critical region at a time (mutual exclusion)
Skeleton
Code for Counting Semaphore
- Counting semaphore is
initialized to "n"
- It then allows n processes into
critical region or allocation of n resources
- wait(sem):
s:=s-1; if s<0 place process on sem.queue
- signal(sem):
s:=s+1; if s <= n then move process from sem.queue
to ready list