Reputation: 404
I was reading a text on semaphores and their operations. The author emphasized that the wait()
and post()
operations of semaphores should be executed atomically, otherwise mutual exclusion of the threads may be violated. Can anybody, please explain to me what he means? I am new to multi-threading by the way
Upvotes: 2
Views: 789
Reputation: 12678
Yes, if wait()
and post()
operations on semaphore are not executed atomically mutual execution of thread can be violated.
For example, consider a semaphore with value S = 1
and processes P1
and P2
try to to execute wait()
simultaneously as below,
At time T0
, T1
process P1
, P2
finds the value of semaphore as S = 1
respectively followed by decrementing the semaphore to acquire the lock and enter the critical section simultaneously violating the mutual execution of threads.
To employ atomicity between wait()
and post()
spin-locking until the lock is obtained is advised.
Upvotes: 0
Reputation: 28920
The operation of context switch, where a task / process is replaced by another by the kernel is asynchronous and undeterministic.
Let's examine the following code:
x++;
seems simple, hah ? However this code is prone to synchronization errors, if x is shared among different tasks / process.
To understand that, you must understand the concept of atomic operation.
Atomic operation are instructions that the processor can execute on a single clock. It usually involves reading a register, writing a register, etc.
back to the code example: What actually happens behind the scenes (assembly) when incrementing a variable is that the cpu reads the value of the variable into a register. then, it increments it. and then it saves it back to the original place it tool it from (memory).
As you can see, a simple operation like this involves 3 cpu steps. context switch can occur between these 3 steps.
Let's take an example of two threads that needs to increment the same variable x.
Let's examine the pseudo assembly code of an imaginary (yet possible) scenario
if x was 3, it appears that it needs to be 5 now, but it will be 4.
Now, let's refer to your original question. a semaphore / mutex is actually a variable. and when a process wants to to take it it increments it.
Upvotes: 2