what is the reason that semaphores mus be atomic

1k views Asked by At

Im learning about semaphores: sem_wait and sem_signal. Resources say that semaphores must be atomic to for implementing mutual exclusion I can't understand why they must be atomic?! what happens if they are not?!

1

There are 1 answers

0
Craig S. Anderson On BEST ANSWER

This is what happens if a mutual semaphore implementation is not atomic. Let's say we use this code to implement the semaphore:

1 while (semaphore == locked) {
2   pause;
3 }
4 semaphore = locked;

Let's say that processor 0 and processor 1 both want to lock the semaphore, and some other processor (#2) has the semaphore. So both processor 0 and 1 are in the while loop starting on line 1.

Once the other processor (#2) unlocks the semaphore, both processors (#0 and #1) could exit their respective while loops because the semaphore is now unlocked.

Now both processor 0 and 1 think they have locked the semaphore. This is bad.

What needs to happens is that the read of the semaphore's value and the write must be atomic with respect to other processors.

Please comment if this isn't clear - I can go into more detail if needed.