<p>A semaphore is a programming concept that is frequently used to solve multi-threading problems.  My question to the community: </p>

<p>What is a semaphore and how do you use it?</p>

[{'answer_id': 34529, 'author': 'Craig H', 'author_id': 2328, 'author_profile': 'https://Stackoverflow.com/users/2328', 'pm_score': -1, 'selected': False, 'text': '<p>A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource.  This keeps two threads from concurrently accesing a resource, which can cause problems.</p>\n'}, {'answer_id': 34560, 'author': 'Mats Fredriksson', 'author_id': 2973, 'author_profile': 'https://Stackoverflow.com/users/2973', 'pm_score': 4, 'selected': False, 'text': '<p>@Craig:</p>\n\n<blockquote>\n  <p>A semaphore is a way to lock a\n  resource so that it is guaranteed that\n  while a piece of code is executed,\n  only this piece of code has access to\n  that resource. This keeps two threads\n  from concurrently accesing a resource,\n  which can cause problems.</p>\n</blockquote>\n\n<p>This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.</p>\n'}, {'answer_id': 40238, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 8, 'selected': False, 'text': '<p>The article <a href="https://barrgroup.com/embedded-systems/how-to/rtos-mutex-semaphore" rel="noreferrer">Mutexes and Semaphores Demystified</a> by Michael Barr is a great short introduction into what makes mutexes and semaphores different, and when they should and should not be used. I\'ve excerpted several key paragraphs here.</p>\n<p>The key point is that mutexes should be used to protect shared resources, while semaphores should be used for signaling. You should generally not use semaphores to protect shared resources, nor mutexes for signaling. There are issues, for instance, with the bouncer analogy in terms of using semaphores to protect shared resources - you can use them that way, but it may cause hard to diagnose bugs.</p>\n<blockquote>\n<p>While mutexes and semaphores have some similarities in their implementation, they should always be used differently.</p>\n<p>The most common (but nonetheless incorrect) answer to the question posed at the top is that mutexes and semaphores are very similar, with the only significant difference being that semaphores can count higher than one. Nearly all engineers seem to properly understand that a mutex is a binary flag used to protect a shared resource by ensuring mutual exclusion inside critical sections of code. But when asked to expand on how to use a &quot;counting semaphore,&quot; most engineers—varying only in their degree of confidence—express some flavor of the textbook opinion that these are used to protect several equivalent resources.</p>\n</blockquote>\n<p>...</p>\n<p>At this point an interesting analogy is made using the idea of bathroom keys as protecting shared resources - the bathroom.  If a shop has a single bathroom, then a single key will be sufficient to protect that resource and prevent multiple people from using it simultaneously.</p>\n<p>If there are multiple bathrooms, one might be tempted to key them alike and make multiple keys - this is similar to a semaphore being mis-used.  Once you have a key you don\'t actually know which bathroom is available, and if you go down this path you\'re probably going to end up using mutexes to provide that information and make sure you don\'t take a bathroom that\'s already occupied.</p>\n<p>A semaphore is the wrong tool to protect several of the essentially same resource, but this is how many people think of it and use it. The bouncer analogy is distinctly different - there aren\'t several of the same type of resource, instead there is one resource which can accept multiple simultaneous users.  I suppose a semaphore can be used in such situations, but rarely are there real-world situations where the analogy actually holds - it\'s more often that there are several of the same type, but still individual resources, like the bathrooms, which cannot be used this way.</p>\n<p>...</p>\n<blockquote>\n<p>The correct use of a semaphore is for signaling from one task to another. A mutex is meant to be taken and released, always in that order, by each task that uses the shared resource it protects. By contrast, tasks that use semaphores either signal or wait—not both. For example, Task 1 may contain code to post (i.e., signal or increment) a particular semaphore when the &quot;power&quot; button is pressed and Task 2, which wakes the display, pends on that same semaphore. In this scenario, one task is the producer of the event signal; the other the consumer.</p>\n</blockquote>\n<p>...</p>\n<p>Here an important point is made that mutexes interfere with real time operating systems in a bad way, causing priority inversion where a less important task may be executed before a more important task because of resource sharing.  In short, this happens when a lower priority task uses a mutex to grab a resource, A, then tries to grab B, but is paused because B is unavailable.  While it\'s waiting, a higher priority task comes along and needs A, but it\'s already tied up, and by a process that isn\'t even running because it\'s waiting for B.  There are many ways to resolve this, but it most often is fixed by altering the mutex and task manager.  The mutex is much more complex in these cases than a binary semaphore, and using a semaphore in such an instance will cause priority inversions because the task manager is unaware of the priority inversion and cannot act to correct it.</p>\n<p>...</p>\n<blockquote>\n<p>The cause of the widespread modern confusion between mutexes and semaphores is historical, as it dates all the way back to the 1974 invention of the Semaphore (capital &quot;S&quot;, in this article) by Djikstra. Prior to that date, none of the interrupt-safe task synchronization and signaling mechanisms known to computer scientists was efficiently scalable for use by more than two tasks. Dijkstra\'s revolutionary, safe-and-scalable Semaphore was applied in both critical section protection and signaling. And thus the confusion began.</p>\n<p>However, it later became obvious to operating system developers, after the appearance of the priority-based preemptive RTOS (e.g., VRTX, ca. 1980), publication of academic papers establishing RMA and the problems caused by priority inversion, and a paper on priority inheritance protocols in 1990, 3 it became apparent that mutexes must be more than just semaphores with a binary counter.</p>\n</blockquote>\n<p>Mutex: resource sharing</p>\n<p>Semaphore: signaling</p>\n<p>Don\'t use one for the other without careful consideration of the side effects.</p>\n'}, {'answer_id': 40282, 'author': 'Michael Haren', 'author_id': 29, 'author_profile': 'https://Stackoverflow.com/users/29', 'pm_score': 6, 'selected': False, 'text': '<p>Mutex: exclusive-member access to a resource</p>\n\n<p>Semaphore: n-member access to a resource</p>\n\n<p>That is, a mutex can be used to syncronize access to a counter, file, database, etc.</p>\n\n<p>A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy.</p>\n'}, {'answer_id': 40410, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 3, 'selected': False, 'text': '<p>A semaphore is an object containing a natural number (i.e. a integer greater or equal to zero) on which two modifying operations are defined. One operation, <code>V</code>, adds 1 to the natural. The other operation, <code>P</code>, decreases the natural number by 1. Both activities are atomic (i.e. no other operation can be executed at the same time as a <code>V</code> or a <code>P</code>).</p>\n\n<p>Because the natural number 0 cannot be decreased, calling <code>P</code> on a semaphore containing a 0 will block the execution of the calling process(/thread) until some moment at which the number is no longer 0 and <code>P</code> can be successfully (and atomically) executed.</p>\n\n<p>As mentioned in other answers, semaphores can be used to restrict access to a certain resource to a maximum (but variable) number of processes.</p>\n'}, {'answer_id': 40473, 'author': 'Patrik Svensson', 'author_id': 936, 'author_profile': 'https://Stackoverflow.com/users/936', 'pm_score': 9, 'selected': False, 'text': '<p>Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.</p>\n\n<p>It\'s simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.</p>\n\n<p>Here is a very pedagogic example in C# :-)</p>\n\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nnamespace TheNightclub\n{\n    public class Program\n    {\n        public static Semaphore Bouncer { get; set; }\n\n        public static void Main(string[] args)\n        {\n            // Create the semaphore with 3 slots, where 3 are available.\n            Bouncer = new Semaphore(3, 3);\n\n            // Open the nightclub.\n            OpenNightclub();\n        }\n\n        public static void OpenNightclub()\n        {\n            for (int i = 1; i &lt;= 50; i++)\n            {\n                // Let each guest enter on an own thread.\n                Thread thread = new Thread(new ParameterizedThreadStart(Guest));\n                thread.Start(i);\n            }\n        }\n\n        public static void Guest(object args)\n        {\n            // Wait to enter the nightclub (a semaphore to be released).\n            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);\n            Bouncer.WaitOne();          \n\n            // Do some dancing.\n            Console.WriteLine("Guest {0} is doing some dancing.", args);\n            Thread.Sleep(500);\n\n            // Let one guest out (release one semaphore).\n            Console.WriteLine("Guest {0} is leaving the nightclub.", args);\n            Bouncer.Release(1);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 73387, 'author': 'shodanex', 'author_id': 11589, 'author_profile': 'https://Stackoverflow.com/users/11589', 'pm_score': 4, 'selected': False, 'text': "<p>Semaphore can also be used as a ... semaphore.\nFor example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.</p>\n\n<p>Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism.\nThe consuming task is waiting on the semaphore\nThe producing task are posting on the semaphore.</p>\n\n<p>This way the consuming task is running when and only when there is data to be dequeued</p>\n"}, {'answer_id': 5975456, 'author': 'MABUTOBRIGHTON', 'author_id': 750219, 'author_profile': 'https://Stackoverflow.com/users/750219', 'pm_score': 2, 'selected': False, 'text': '<p>A hardware or software flag. In multi tasking systems , a semaphore is as variable with a value that indicates the status of a common resource.A process needing the resource checks the semaphore to determine the resources status and then decides how to proceed.</p>\n'}, {'answer_id': 9103974, 'author': 'bestsss', 'author_id': 554431, 'author_profile': 'https://Stackoverflow.com/users/554431', 'pm_score': 0, 'selected': False, 'text': '<p>This is an old question but one of the most interesting uses of semaphore is a read/write lock and it has not been explicitly mentioned.</p>\n\n<p>The r/w locks works in simple fashion: consume one permit for a reader and all permits for writers.\nIndeed, a trivial implementation of a r/w lock but requires metadata modification on read (actually twice) that can become a bottle neck, still significantly better than a mutex or lock.</p>\n\n<p>Another downside is that writers can be started rather easily as well unless the semaphore is a fair one or the writes acquire permits in multiple requests, in such case they need an explicit mutex between themselves.</p>\n\n<p>Further <a href="http://doc.qt.nokia.com/qq/qq11-mutex.html" rel="nofollow">read</a>:</p>\n'}, {'answer_id': 21761646, 'author': 'Columbia Student in Jae Class', 'author_id': 3307208, 'author_profile': 'https://Stackoverflow.com/users/3307208', 'pm_score': 2, 'selected': False, 'text': '<p>So imagine everyone is trying to go to the bathroom and there\'s only a certain number of keys to the bathroom. Now if there\'s not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.</p>\n\n<p>Now imagine two processes trying to go to the bathroom at the same time. That\'s not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).</p>\n\n<p>There are also differences between binary/mutex &amp; counting semaphores. </p>\n\n<p>Check out the lecture notes at <a href="http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html" rel="nofollow">http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html</a>.</p>\n'}, {'answer_id': 23545993, 'author': 'aspen100', 'author_id': 2112500, 'author_profile': 'https://Stackoverflow.com/users/2112500', 'pm_score': 4, 'selected': False, 'text': '<p>There are two essential concepts to building concurrent programs - synchronization and mutual exclusion. We will see how these two types of locks (semaphores are more generally a kind of locking mechanism) help us achieve synchronization and mutual exclusion.</p>\n\n<p>A semaphore is a programming construct that helps us achieve concurrency, by implementing both synchronization and mutual exclusion. Semaphores are of two types, Binary and Counting.</p>\n\n<p>A semaphore has two parts : a counter, and a list of tasks waiting to access a particular resource. A semaphore performs two operations : wait (P) [this is like acquiring a lock], and release (V)[ similar to releasing a lock] - these are the only two operations that one can perform on a semaphore. In a binary semaphore, the counter logically goes between 0 and 1. You can think of it as being similar to a lock with two values : open/closed. A counting semaphore has multiple values for count.</p>\n\n<p>What is important to understand is that the semaphore counter keeps track of the number of tasks that do not have to block, i.e., they can make progress. Tasks block, and add themselves to the semaphore\'s list only when the counter is zero. Therefore, a task gets added to the list in the P() routine if it cannot progress, and "freed" using the V() routine.</p>\n\n<p>Now, it is fairly obvious to see how binary semaphores can be used to solve synchronization and mutual exclusion - they are essentially locks.</p>\n\n<p>ex. Synchronization:</p>\n\n<pre><code>thread A{\nsemaphore &amp;s; //locks/semaphores are passed by reference! think about why this is so.\nA(semaphore &amp;s): s(s){} //constructor\nfoo(){\n...\ns.P();\n;// some block of code B2\n...\n}\n\n//thread B{\nsemaphore &amp;s;\nB(semaphore &amp;s): s(s){} //constructor\nfoo(){\n...\n...\n// some block of code B1\ns.V();\n..\n}\n\nmain(){\nsemaphore s(0); // we start the semaphore at 0 (closed)\nA a(s);\nB b(s);\n}\n</code></pre>\n\n<p>In the above example, B2 can only execute after B1 has finished execution. Let\'s say thread A comes executes first - gets to sem.P(), and waits, since the counter is 0 (closed). Thread B comes along, finishes B1, and then frees thread A - which then completes B2. So we achieve synchronization.</p>\n\n<p>Now let\'s look at mutual exclusion with a binary semaphore:</p>\n\n<pre><code>thread mutual_ex{\nsemaphore &amp;s;\nmutual_ex(semaphore &amp;s): s(s){} //constructor\nfoo(){\n...\ns.P();\n//critical section\ns.V();\n...\n...\ns.P();\n//critical section\ns.V();\n...\n\n}\n\nmain(){\nsemaphore s(1);\nmutual_ex m1(s);\nmutual_ex m2(s);\n}\n</code></pre>\n\n<p>The mutual exclusion is quite simple as well - m1 and m2 cannot enter the critical section at the same time. So each thread is using the same semaphore to provide mutual exclusion for its two critical sections. Now, is it possible to have greater concurrency? Depends on the critical sections. (Think about how else one could use semaphores to achieve mutual exclusion.. hint hint : do i necessarily only need to use one semaphore?)</p>\n\n<p>Counting semaphore: A semaphore with more than one value. Let\'s look at what this is implying - a lock with more than one value?? So open, closed, and ...hmm. Of what use is a multi-stage-lock in mutual exclusion or synchronization?</p>\n\n<p>Let\'s take the easier of the two:</p>\n\n<p>Synchronization using a counting semaphore: Let\'s say you have 3 tasks - #1 and 2 you want executed after 3. How would you design your synchronization?</p>\n\n<pre><code>thread t1{\n...\ns.P();\n//block of code B1\n\nthread t2{\n...\ns.P();\n//block of code B2\n\nthread t3{\n...\n//block of code B3\ns.V();\ns.V();\n}\n</code></pre>\n\n<p>So if your semaphore starts off closed, you ensure that t1 and t2 block, get added to the semaphore\'s list. Then along comes all important t3, finishes its business and frees t1 and t2. What order are they freed in? Depends on the implementation of the semaphore\'s list. Could be FIFO, could be based some particular priority,etc. (Note : think about how you would arrange your P\'s and V;s if you wanted t1 and t2 to be executed in some particular order, and if you weren\'t aware of the implementation of the semaphore)</p>\n\n<p>(Find out : What happens if the number of V\'s is greater than the number of P\'s?)</p>\n\n<p>Mutual Exclusion Using counting semaphores: I\'d like you to construct your own pseudocode for this (makes you understand things better!) - but the fundamental concept is this : a counting semaphore of counter = N allows N tasks to enter the critical section freely. What this means is you have N tasks (or threads, if you like) enter the critical section, but the N+1th task gets blocked (goes on our favorite blocked-task list), and only is let through when somebody V\'s the semaphore at least once. So the semaphore counter, instead of swinging between 0 and 1, now goes between 0 and N, allowing N tasks to freely enter and exit, blocking nobody!</p>\n\n<p>Now gosh, why would you need such a stupid thing? Isn\'t the whole point of mutual exclusion to not let more than one guy access a resource?? (Hint Hint...You don\'t always only have one drive in your computer, do you...?)</p>\n\n<p><em>To think about</em> : Is mutual exclusion achieved by having a counting semaphore alone? What if you have 10 instances of a resource, and 10 threads come in (through the counting semaphore) and try to use the first instance?</p>\n'}, {'answer_id': 44971803, 'author': 'NKumar', 'author_id': 5532090, 'author_profile': 'https://Stackoverflow.com/users/5532090', 'pm_score': 5, 'selected': False, 'text': '<p>Consider, a taxi that can accommodate a total of 3(<em>rear</em>)+2(<em>front</em>) persons including the driver. So, a <strong><code>semaphore</code></strong> allows only 5 persons inside a car at a time.\nAnd a <strong><code>mutex</code></strong> allows only 1 person on a single seat of the car.</p>\n\n<p>Therefore, <strong><code>Mutex</code></strong> is to allow exclusive access for a resource (<em>like an OS thread</em>) while a <strong><code>Semaphore</code></strong> is to allow access for <strong>n</strong> number of resources at a time.</p>\n'}, {'answer_id': 52093990, 'author': 'Volodymyr', 'author_id': 1245166, 'author_profile': 'https://Stackoverflow.com/users/1245166', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment.\n<a href="https://i.stack.imgur.com/cDXIV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cDXIV.png" alt="enter image description here"></a></p>\n\n<pre><code>ExecutorService executor = Executors.newFixedThreadPool(7);\n\nSemaphore semaphore = new Semaphore(4);\n\nRunnable longRunningTask = () -&gt; {\n    boolean permit = false;\n    try {\n        permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);\n        if (permit) {\n            System.out.println("Semaphore acquired");\n            Thread.sleep(5);\n        } else {\n            System.out.println("Could not acquire semaphore");\n        }\n    } catch (InterruptedException e) {\n        throw new IllegalStateException(e);\n    } finally {\n        if (permit) {\n            semaphore.release();\n        }\n    }\n};\n\n// execute tasks\nfor (int j = 0; j &lt; 10; j++) {\n    executor.submit(longRunningTask);\n}\nexecutor.shutdown();\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>Semaphore acquired\nSemaphore acquired\nSemaphore acquired\nSemaphore acquired\nCould not acquire semaphore\nCould not acquire semaphore\nCould not acquire semaphore\n</code></pre>\n\n<p>Sample code from the <a href="https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/#semaphores" rel="noreferrer">article</a></p>\n'}, {'answer_id': 57520626, 'author': 'sumit', 'author_id': 10828672, 'author_profile': 'https://Stackoverflow.com/users/10828672', 'pm_score': 2, 'selected': False, 'text': '<p>Semaphores are act like thread limiters. </p>\n\n<p><strong>Example:</strong> If you have a pool of 100 threads and you want to perform some DB operation. If 100 threads access the DB at a given time, then there may be locking issue in DB so we can use semaphore which allow only limited thread at a time.Below Example allow only one thread at a time. When a thread call the <code>acquire()</code> method, it will then get the access and after calling the <code>release()</code> method, it will release the acccess so that next thread will get the access.</p>\n\n<pre><code>    package practice;\n    import java.util.concurrent.Semaphore;\n\n    public class SemaphoreExample {\n        public static void main(String[] args) {\n            Semaphore s = new Semaphore(1);\n            semaphoreTask s1 = new semaphoreTask(s);\n            semaphoreTask s2 = new semaphoreTask(s);\n            semaphoreTask s3 = new semaphoreTask(s);\n            semaphoreTask s4 = new semaphoreTask(s);\n            semaphoreTask s5 = new semaphoreTask(s);\n            s1.start();\n            s2.start();\n            s3.start();\n            s4.start();\n            s5.start();\n        }\n    }\n\n    class semaphoreTask extends Thread {\n        Semaphore s;\n        public semaphoreTask(Semaphore s) {\n            this.s = s;\n        }\n        @Override\n        public void run() {\n            try {\n                s.acquire();\n                Thread.sleep(1000);\n                System.out.println(Thread.currentThread().getName()+" Going to perform some operation");\n                s.release();\n            } catch (InterruptedException e) {\n                e.printStackTrace();\n            }\n        } \n    }\n</code></pre>\n'}, {'answer_id': 71113133, 'author': 'Pithikos', 'author_id': 474563, 'author_profile': 'https://Stackoverflow.com/users/474563', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Mutex is just a boolean while semaphore is a counter</strong>.</p>\n<p>Both are used to lock part of code so it's not accessed by too many threads.</p>\n<p>Example</p>\n<pre><code>lock.set()\na += 1\nlock.unset()\n</code></pre>\n<p>Now if <code>lock</code> was a mutex, it means that it will always be locked or unlocked (a boolean under the surface) regardless how many threads try access the protected snippet of code. While locked, any other thread would just wait until it's unlocked/unset by the previous thread.</p>\n<p>Now imagine if instead <code>lock</code> was under the hood a counter with a predefined MAX value (say 2 for our example). Then if 2 threads try to access the resource, then lock would get its value increased to 2. If a 3rd thread then tried to access it, it would simply wait for the counter to go below 2 and so on.</p>\n<p><strong>If lock as a semaphore had a max of 1, then it would be acting exactly as a mutex.</strong></p>\n"}]
['https://Stackoverflow.com/questions/34519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931/']