Home > Software engineering >  Atomic instructions in semaphores
Atomic instructions in semaphores

Time:11-02

I am confused what it means for semaphores to be atomic. The definition of wait and signal is below.

wait(S){
    while ( S<= 0)
        ; // Busy wait
        S--;
}


signal(S) {
    S  ;
}

The book says

all modifications to the integer value of the sophomore in the wait() and signal() operations must be executed atomically. That is, when one process modifies the semaphore value, no other process can simultaneously modify the same semaphore value

Does this mean that no other instructions can execute in-between while(S<=0) and S--? and at what point is the process done modifying the semaphore value? is this when it finally decrements S--?

CodePudding user response:

Does this mean that no other instructions can execute in-between while(S<=0) and S--?

No. It means all modifications (such as S--) must be done atomically, that is, no other process can simultaneously attempt to modify S, for example, by executing the S in signal.

At what point is the process done modifying the semaphore value? is this when it finally decrements S--?

Each modification must be atomic, as the explanation says. So it's done modifying the value at the end of each modification. It may modify it again, but that would be a distinct modification that must also be atomic.

You can think of an "atomic modification" as one that does not overlap any other atomic access or modification. Were S and S-- not atomic, an operation could get lost if, for example, two processes execute S and their operations overlap. They could both read S, both increment S, then both write S, resulting in S only getting incremented once.

CodePudding user response:

What it means for any operation to be atomic is: Either it happens or it doesn't. If some thread A performs an atomic operation on some collection of data or on some object, and thread B examines the object/data, then thread B must either see the object/data as it was before the operation started or, as it was after the operation finished. "Atomic" means that it's impossible for thread B to see the object/data in a half-way done state.

We can provide atomicity by using synchronized blocks or ReentrantLock objects when accessing data, but if somebody tells you that some object is atomic, then what they are saying is, all of the operations that you can perform on it* are automatically guaranteed to be atomic, without you having to explicitly lock anything.


* Except maybe for special cases, called out in the object's documentation.

  • Related