首页 > 试题广场 >

Show how to implement the wait

[问答题]
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;
}

发表于 2018-03-18 22:02:22 回复(0)