concurrencylockingmutexsemaphore

What is the difference between lock, mutex and semaphore?


I've heard these words related to concurrent programming, but what's the difference between lock, mutex and semaphore?


Solution

  • A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes, a lock must be released by that same thread that acquired it. Some locks can be acquired multiple times by the same thread without causing a deadlock, but must be released the same amount of times.

    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.

    A semaphore kan be acquired by one thread and released by a different thread.

    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.