Semaphore is a data structure that is used to make sure that multiple processes do not access a common resource or a critical section at the same time, in parallel programming environments. Semaphores are used to avoid dead locks and race conditions. Mutex (Mutual Exclusion Object) is also used to avoid access to a common resource at the same time by several concurrent processes.
What is a Semaphore?
Semaphore is a data structure that is used to provide mutual exclusion to critical sections. Semaphores mainly support two operations called wait (historically known as P) and signal (historically known as V). The wait operation blocks a process until the semaphore is open and the signal operation allows another process (thread) to enter. Each semaphore is associated with a queue of waiting processes. When the wait operation is called by a thread, if the semaphore is open, the thread can continue. If the semaphore is closed when the wait operation is called by a thread, the thread is blocked and it has to wait in the queue. The signal operation opens a semaphore and if there is a thread already waiting in the queue, that process is allowed to proceed and if there are no threads waiting in the queue the signal is remembered for the next threads. There are two types of semaphores called mutex semaphores and counting semaphores. Mutex semaphores allow a single access to a resource and counting semaphores allow multiple threads to access a resource (which has several units available).
What is a Mutex?
When a computer application is started, it will create a mutex and attach it to a resource. When the resource is used by a thread, it is locked and other threads cannot use it. If another thread wants to use the same resource, it will have to make a request. Then that thread will be placed in a queue until the first thread is finished with the resource. When the first thread is finished with the resource, lock will be removed and the thread that is waiting in the queue can get access to the resource. If there are multiple threads waiting in the queue, they are given access in a rotating basis. Practically, when the mutex alternates the access to a resource between several threads, it will be visible as multiple threads are consuming a resource at the same time. But internally only a single thread is accessing the resource at a given time.
What is the difference between Semaphore and Mutex?
Even though, both the semaphores and mutex objects are used to achieve mutual exclusion in parallel programming environments, they have some differences. A mutex object only allows a single thread to consume a resource or a critical section, whereas semaphores allow a restricted number of simultaneous accesses to a resource (under a maximum allowed number). With mutex objects, other threads who want to access the resource have to wait in a queue, until the current thread is finished using the resource.