• support@answerspoint.com

A semaphore is a blocking synchronisation primitive. Describe how they work with the aid of pseudo-code.

4141

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.

Example :-

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();

}

}

0Answer


Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 4141 times
  • active 9 years ago

Best Rated Questions