What is the difference between above two?
This question came to my mind because I found that
Monitors and locks provide mutual exclusion
Semaphores and conditional variables provide synchronization
Is this true?
Also while searching I found this article
Any clarifications please.
A mutual exclusion (mutex) is a program object that prevents simultaneous access to a shared resource. This concept is used in concurrent programming with a critical section, a piece of code in which processes or threads access a shared resource.
Processes Synchronization or Synchronization is the way by which processes that share the same memory space are managed in an operating system. It helps maintain the consistency of data by using variables or hardware so that only one process can make changes to the shared memory at a time.
Condition Synchronization (or merely synchronization) is any mechanism that protects areas of memory from being modified by two different threads at the same time.
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.
Mutual exclusion means that only a single thread should be able to access the shared resource at any given point of time. This avoids the race conditions between threads acquireing the resource. Monitors and Locks provide the functionality to do so.
Synchronization means that you synchronize/order the access of multiple threads to the shared resource.
Consider the example:
If you have two threads, Thread 1
& Thread 2
.Thread 1
and Thread 2
execute in parallel but before Thread 1
can execute say a statement A
in its sequence it is a must that Thread 2
should execute a statement B
in its sequence. What you need here is synchronization. A semaphore provides that. You put a semapohore wait before the statement A
in Thread 1
and you post to the semaphore after statement B
in Thread 2
.
This ensures the synchronization you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With