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.
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.