What Is Mutex and Semaphore in Java? What Is the Main Difference

What is the difference between lock, mutex and semaphore?

A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes.

A mutex is the same as a lock but it can be system wide (shared by multiple processes).

A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.

For a more detailed post about the differences between mutex and semaphore read here.

You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time.

The descriptions are from a .NET perspective and might not be 100% accurate for all OS/Languages.

What is the difference between semaphore and mutex in implementation?

Assuming you know the basic differences between a sempahore and mutex :

For fast, simple synchronization, use a critical section.

To synchronize threads across process boundaries, use mutexes.

To synchronize access to limited resources, use a semaphore.

Apart from the fact that mutexes have an owner, the two objects may be optimized for different usage. Mutexes are designed to be held only for a short time; violating this can cause poor performance and unfair scheduling. For example, a running thread may be permitted to acquire a mutex, even though another thread is already blocked on it, creating a deadlock. Semaphores may provide more fairness, or fairness can be forced using several condition variables.

Difference between Mutex and Semaphore=1?

Think of Mutex as being in a subset of the definition of a semaphore.

There is a good answer on Stack Overflow here: Difference between binary semaphore and mutex .

Mutex can be released only by thread that had acquired it, while you
can signal semaphore from any other thread (or process), so semaphores
are more suitable for some synchronization problems like
producer-consumer.



Related Topics



Leave a reply



Submit