I've heard these words related to concurrent programming, but what's the difference between them?
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
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. You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time. |
|||||||||||||||||||||
|
|
There are a lot of misconceptions regarding these words. This is from a previous post (https://stackoverflow.com/a/24582076/3163691) which fits superb here: 1) Critical Section= User object used for allowing the execution of just one active thread from many others within one process. The other non selected threads are put to sleep. [No interprocess capability, very primitive object]. 2) Mutex Semaphore (aka Mutex)= Kernel object used for allowing the execution of just one active thread from many others, among different processes. The other non selected threads are put to sleep. This object supports thread ownership, thread termination notification, recursion (multiple 'acquire' calls from same thread) and 'priority inversion avoidance'. [Interprocess capability, very safe to use, a kind of 'high level' synchronization object]. 3) Counting Semaphore (aka Semaphore)= Kernel object used for allowing the execution of a group of active threads from many others. The other non selected threads are put to sleep. [Interprocess capability however not very safe to use because it lacks following 'mutex' attributes: thread termination notification, recursion?, 'priority inversion avoidance'?, etc]. 4) And now, talking about 'spinlocks', first some definitions: Critical Region= A region of memory shared by 2 or more processes. Lock= A variable whose value allows or denies the entrance to a 'critical region'. (It could be implemented as a simple 'boolean flag'). Busy waiting= Continuosly testing of a variable until some value appears. Finally: Spin-lock (aka Spinlock)= A lock which uses busy waiting. (The acquiring of the lock is made by xchg or similar atomic operations). [No thread sleeping, mostly used at kernel level only. Ineffcient for User level code]. As a last comment, I am not sure but I can bet you some big bucks that the above first 3 synchronizing objects (#1, #2 and #3) make use of this simple beast (#4) as part of their implementation. Have a good day!. References: -Real-Time Concepts for Embedded Systems by Qing Li with Caroline Yao (CMP Books). -Modern Operating Systems (3rd) by Andrew Tanenbaum (Pearson Education International). -Programming Applications for Microsoft Windows (4th) by Jeffrey Richter (Microsoft Programming Series). Also, you can take a look at look at: https://stackoverflow.com/a/24586803/3163691 |
|||||||||||||||||||||
|
|
Take a look at Multithreading Tutorial by John Kopplin. In the section Synchronization Between Threads, he explain the differences among event, lock, mutex, semaphore, waitable timer
|
||||
|
|
|
I will try to cover it with examples: Lock: One example where you would use
Semaphore: Let's say you have a pool of connections, then an single thread might reserve one element in the pool by waiting for the semaphore to get a connection. It then uses the connection and when work is done releases the connection by releasing the semaphore. Code example that I love is one of bouncer given by @Patric - here it goes:
Mutex It is pretty much Good example on creating global mutex is by @deepee
then use like:
Hope this saves you some time. |
||||
|
|
|
Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have
For both locks/semaphores, trying to call For locks in state state 0, if same thread that had previously called From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore). What causes a lot of confusion is that, in practice they are many variations of this high-level definition. Important variations to consider:
These depends on your book / lecturer / language / library / environment. C, C++ (pthreads)
python (threading.py)
Java (java.util.concurrent)
In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead. |
|||
|
|
|
Wikipedia has a great section on the differences between Semaphores and Mutexes:
|
||||
|
|
|
My understanding is that a mutex is only for use within a single process, but across its many threads, whereas a semaphore may be used across multiple processes, and across their corresponding sets of threads. Also, a mutex is binary (it's either locked or unlocked), whereas a semaphore has a notion of counting, or a queue of more than one lock and unlock requests. Could someone verify my explanation? I'm speaking in the context of Linux, specifically Red Hat Enterprise Linux (RHEL) version 6, which uses kernel 2.6.32. |
|||||||||||||
|
|
Mutex: Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue. Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." (A mutex is really a semaphore with value 1.) Semaphore: Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue. Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." |
|||
|
|
|
Using C programming on a Linux variant as a base case for examples. Lock: • Usually a very simple construct binary in operation either locked or unlocked • No concept of thread ownership, priority, sequencing etc. • Usually a spin lock where the thread continuously checks for the locks availability. • Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc. • Usually requires hardware support for atomic operation. File Locks: • Usually used to coordinate access to a file via multiple processes. • Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock. • Example : flock, fcntl etc.. Mutex: • Mutex function calls usually work in kernel space and result in system calls. • It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it. • Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE). • Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc. • Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems. Semaphore: • This is a kernel maintained integer whose values is not allowed to fall below zero. • It can be used to synchronize processes. • The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available. • A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore. |
|||
|
|