Synchronization primitives: Mutex and Semaphore (Differences between Mutex and Semaphore) - Article 12
Hi Folks,
Sorry,
had to take a long break. In this article, let's summarize the differences
between Mutex and Semaphore and this is the last article in the series. In the
coming articles we shall discuss more about OO, Design, C++, etc and revisit synchronization as and when
needed.
Mutex
|
Semaphore
|
|
1
|
Mutex is a locking
mechanism only to ensure mutual exclusion, that is only one thread or process
is allowed to execute the code in critical section.
|
Semaphore can be
used for locking, signalling and variety of problems as we have seen in the
examples.
|
2
|
Mutex is owned and
only thread that has locked the mutex can unlock it.
|
Semaphore does not
have ownership, anybody can unlock a semaphore.
|
3
|
Process wide.
|
System wide.
|
4
|
Mutex is used to
synchronize threads.
|
Semaphore is used to
synchronize threads/processes.
|
5
|
Simpler to use.
|
Complex semantics.
|
To
answer the "When to use what question", mutex is preferred when only locking is
required within threads, i.e., if the requirement is only to protect data or a
critical section of code, mutex should be used as it is simple.
For
all other synchronization problems like serialization, simultaneous access to
shared resources, etc, mutex can't be used. The only other choice is semaphore.
With this, we shall ramp up synchronization.
Very Useful & precise explanation. Thankyou.
ReplyDelete