Show how to implement the wait( ) and signal( ) semaphore operations in multiprocessor environments using the TestAndSet( ) instruction.The solution should exhibit minimal busy waiting.
Here is the pseudocode for implementing the operations:
int guard = 0;
int semaphore_value = 0;
wait()
{
while (TestAndSet (&guard) == 1);
if (semaphore_value == 0) {
atomically add process to a queue of processes
waiting for the semaphore and set guard to 0;
} else {
semaphore_value --;
guard=0;
}
}
signal ()
{
while (TestAndSet (&guard) == 1);
if (semaphore_value == 0 &&
there is a process on the wait queue)
wake up the first process in the queue
of waiting processes
else
semaphore_value++;
guard=0;
}