<p>Is there any difference between a binary semaphore and mutex or are they essentially the same?</p>

[{'answer_id': 62883, 'author': 'Mladen Janković', 'author_id': 6300, 'author_profile': 'https://Stackoverflow.com/users/6300', 'pm_score': 9, 'selected': False, 'text': '<ul>\n<li>A <strong>mutex</strong> can be released only by <strong>the thread that had acquired it</strong>. <br></li>\n<li>A <strong>binary semaphore</strong> can be signaled <strong>by any thread</strong> (or process).</li>\n</ul>\n\n<p>so semaphores are more suitable for some synchronization problems like producer-consumer.</p>\n\n<p>On Windows, binary semaphores are more like event objects than mutexes.</p>\n'}, {'answer_id': 63084, 'author': 'Casey Barker', 'author_id': 7046, 'author_profile': 'https://Stackoverflow.com/users/7046', 'pm_score': 1, 'selected': False, 'text': '<p>The answer may depend on the target OS.  For example, at least one RTOS implementation I\'m familiar with will allow multiple sequential "get" operations against a single OS mutex, so long as they\'re all from within the same thread context.  The multiple gets must be replaced by an equal number of puts before another thread will be allowed to get the mutex.  <em>This differs from binary semaphores, for which only a single get is allowed at a time, regardless of thread contexts.</em></p>\n\n<p>The idea behind this type of mutex is that you protect an object by only allowing a single context to modify the data at a time.  Even if the thread gets the mutex and then calls a function that further modifies the object (and gets/puts the protector mutex around its own operations), the operations should still be safe because they\'re all happening under a single thread.</p>\n\n<pre><code>{\n    mutexGet();  // Other threads can no longer get the mutex.\n\n    // Make changes to the protected object.\n    // ...\n\n    objectModify();  // Also gets/puts the mutex.  Only allowed from this thread context.\n\n    // Make more changes to the protected object.\n    // ...\n\n    mutexPut();  // Finally allows other threads to get the mutex.\n}\n</code></pre>\n\n<p>Of course, when using this feature, you must be certain that all accesses within a single thread really are safe!</p>\n\n<p>I\'m not sure how common this approach is, or whether it applies outside of the systems with which I\'m familiar.  For an example of this kind of mutex, see the ThreadX RTOS.</p>\n'}, {'answer_id': 86021, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 10, 'selected': False, 'text': '<p>They are <strong>NOT</strong> the same thing.  They are used for different purposes!<br>\nWhile both types of semaphores have a full/empty state and use the same API, their usage is very different.  </p>\n\n<p><strong>Mutual Exclusion Semaphores</strong><br>\nMutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..). </p>\n\n<p>A Mutex semaphore is "owned" by the task that takes it.  If Task B attempts to semGive a mutex currently held by Task A, Task B\'s call will return an error and fail.</p>\n\n<p>Mutexes always use the following sequence:  </p>\n\n<pre>\n  - SemTake\n  - Critical Section\n  - SemGive</pre>\n\n<p>Here is a simple example:</p>\n\n<pre>\n  Thread A                     Thread B\n   Take Mutex\n     access data\n     ...                        Take Mutex  &lt;== Will block\n     ...\n   Give Mutex                     access data  &lt;== Unblocks\n                                  ...\n                                Give Mutex\n</pre>\n\n<p><strong>Binary Semaphore</strong><br>\nBinary Semaphore address a totally different question:  </p>\n\n<ul>\n<li>Task B is pended waiting for something to happen (a sensor being tripped for example).</li>\n<li>Sensor Trips and an Interrupt Service Routine runs. It needs to notify a task of the trip.</li>\n<li>Task B should run and take appropriate actions for the sensor trip. Then go back to waiting.</li>\n</ul>\n\n<pre><code>\n   Task A                      Task B\n   ...                         Take BinSemaphore   &lt;== wait for something\n   Do Something Noteworthy\n   Give BinSemaphore           do something    &lt;== unblocks\n</code></pre>\n\n<p>Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.<br>\nAgain, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled.<br>\nIt typically makes little sense for the same task to so a give and a take on the same binary semaphore.</p>\n'}, {'answer_id': 128892, 'author': 'ppi', 'author_id': 2044155, 'author_profile': 'https://Stackoverflow.com/users/2044155', 'pm_score': 6, 'selected': False, 'text': '<p>Their synchronization semantics are very different:</p>\n\n<ul>\n<li>mutexes allow serialization of access to a given resource i.e. multiple threads wait for a lock, one at a time and as previously said, the thread <em>owns</em> the lock until it is done: <strong>only</strong> this particular thread can unlock it.</li>\n<li>a binary semaphore is a counter with value 0 and 1: a task blocking on it until <strong>any</strong> task does a sem_post. The semaphore advertises that a resource is available, and it provides the mechanism to wait until it is signaled as being available.</li>\n</ul>\n\n<p>As such one can see a mutex as a token passed from task to tasks and a semaphore as traffic red-light (it <strong>signals</strong> someone that it can proceed).</p>\n'}, {'answer_id': 204524, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>On Windows, there are two differences between mutexes and binary semaphores:</p>\n\n<ol>\n<li><p>A mutex can only be released by the thread which has ownership, i.e. the thread which previously called the Wait function, (or which took ownership when creating it). A semaphore can be released by any thread.</p></li>\n<li><p>A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.</p></li>\n</ol>\n'}, {'answer_id': 311612, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Mutex work on blocking critical region, But Semaphore work on count.</p>\n'}, {'answer_id': 311648, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': 5, 'selected': False, 'text': '<p>At a theoretical level, they are no different semantically.  You can implement a mutex using semaphores or vice versa (see <a href="http://www.picturel.com/ucr/node32.html" rel="noreferrer">here</a> for an example).  In practice, the implementations are different and they offer slightly different services.</p>\n<p>The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism.  In oracle-speak, mutexes are known as <a href="http://dbataj.blogspot.com/2007/10/oracle-latch.html" rel="noreferrer">latches</a> and semaphores are known as <a href="http://www.dba-oracle.com/art_dbazine_waits.htm" rel="noreferrer">waits</a>.</p>\n<p>At the lowest level, they use some sort of atomic <a href="http://en.wikipedia.org/wiki/Test-and-set" rel="noreferrer">test and set</a> mechanism.  This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that <a href="http://en.wikipedia.org/wiki/Atomic_operation" rel="noreferrer">cannot be interrupted</a>.  This means that you can acquire a mutex and test to see if anyone else had it before you.</p>\n<p>A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex.   A key point here is that there is no interaction with the <a href="http://en.wikipedia.org/wiki/Scheduling_(computing)" rel="noreferrer">scheduler</a>, so we have no idea (and don\'t care) who has set the lock.  Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a <a href="http://en.wikipedia.org/wiki/Spinlock" rel="noreferrer">spin-lock</a>.  A spin lock is an algorithm like:</p>\n<pre><code>Count down from 5000:\n     i. Execute the test-and-set instruction\n    ii. If the mutex is clear, we have acquired it in the previous instruction \n        so we can exit the loop\n   iii. When we get to zero, give up our time slice.\n</code></pre>\n<p>When we have finished executing our protected code (known as a <a href="http://en.wikipedia.org/wiki/Critical_section" rel="noreferrer">critical section</a>) we just set the mutex value to zero or whatever means \'clear.\'  If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource.  Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.</p>\n<p>A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would.  Semaphores are incremented and decremented and used to <a href="http://en.wikipedia.org/wiki/Blocking_(scheduling)" rel="noreferrer">block</a> tasks until something else is ready.  See <a href="http://en.wikipedia.org/wiki/Producer-consumer_problem" rel="noreferrer">Producer/Consumer Problem</a> for a simple example of this.  Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1.  Posting to a semaphore has the effect of waking up a waiting process.</p>\n<p>A basic semaphore algorithm looks like:</p>\n<pre><code>(somewhere in the program startup)\nInitialise the semaphore to its start-up value.\n\nAcquiring a semaphore\n   i. (synchronised) Attempt to decrement the semaphore value\n  ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.\n\nPosting a semaphore\n   i. (synchronised) Increment the semaphore value\n  ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.  \n iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.\n</code></pre>\n<p>In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.</p>\n<p>EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine.  You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running.  Spinlocks are only useful on multi-processor architectures.</p>\n'}, {'answer_id': 346678, 'author': 'dlinsin', 'author_id': 198, 'author_profile': 'https://Stackoverflow.com/users/198', 'pm_score': 9, 'selected': False, 'text': '<p><a href="http://koti.mbnet.fi/niclasw/MutexSemaphore.html" rel="noreferrer">The Toilet example</a> is an enjoyable analogy:</p>\n\n<blockquote>\n  <p>Mutex:</p>\n  \n  <p>Is a key to a toilet. One person can\n  have the key - occupy the toilet - at\n  the time. When finished, the person\n  gives (frees) the key to the next\n  person in the queue.</p>\n  \n  <p>Officially: "Mutexes are typically\n  used to serialise access to a section\n  of  re-entrant code that cannot be\n  executed concurrently by more than one\n  thread. A mutex object only allows one\n  thread into a controlled section,\n  forcing other threads which attempt to\n  gain access to that section to wait\n  until the first thread has exited from\n  that section." Ref: Symbian Developer\n  Library</p>\n  \n  <p>(A mutex is really a semaphore with\n  value 1.)</p>\n  \n  <p>Semaphore:</p>\n  \n  <p>Is the number of free identical toilet\n  keys. Example, say we have four\n  toilets with identical locks and keys.\n  The semaphore count - the count of\n  keys - is set to 4 at beginning (all\n  four toilets are free), then the count\n  value is decremented as people are\n  coming in. If all toilets are full,\n  ie. there are no free keys left, the\n  semaphore count is 0. Now, when eq.\n  one person leaves the toilet,\n  semaphore is increased to 1 (one free\n  key), and given to the next person in\n  the queue.</p>\n  \n  <p>Officially: "A semaphore restricts the\n  number of simultaneous users of a\n  shared resource up to a maximum\n  number. Threads can request access to\n  the resource (decrementing the\n  semaphore), and can signal that they\n  have finished using the resource\n  (incrementing the semaphore)." Ref:\n  Symbian Developer Library</p>\n</blockquote>\n'}, {'answer_id': 1541938, 'author': 'teki', 'author_id': 103267, 'author_profile': 'https://Stackoverflow.com/users/103267', 'pm_score': 7, 'selected': False, 'text': '<p>Nice articles on the topic:</p>\n\n<ul>\n<li><a href="https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-1-semaphores/" rel="noreferrer">MUTEX VS. SEMAPHORES – PART 1: SEMAPHORES</a></li>\n<li><a href="https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-2-the-mutex/" rel="noreferrer">MUTEX VS. SEMAPHORES – PART 2: THE MUTEX</a></li>\n<li><a href="https://blog.feabhas.com/2009/10/mutex-vs-semaphores-%E2%80%93-part-3-final-part-mutual-exclusion-problems/" rel="noreferrer">MUTEX VS. SEMAPHORES – PART 3 (FINAL PART): MUTUAL EXCLUSION PROBLEMS</a></li>\n</ul>\n\n<p><strong>From part 2:</strong></p>\n\n<blockquote>\n  <p>The mutex is similar to the principles\n  of the binary semaphore with one\n  significant difference: the principle\n  of ownership. Ownership is the simple\n  concept that when a task locks\n  (acquires) a mutex only it can unlock\n  (release) it. If a task tries to\n  unlock a mutex it hasn’t locked (thus\n  doesn’t own) then an error condition\n  is encountered and, most importantly,\n  the mutex is not unlocked. If the\n  mutual exclusion object doesn\'t have\n  ownership then, irrelevant of what it\n  is called, it is not a mutex.</p>\n</blockquote>\n'}, {'answer_id': 2757170, 'author': 'Mickey', 'author_id': 331291, 'author_profile': 'https://Stackoverflow.com/users/331291', 'pm_score': 3, 'selected': False, 'text': '<p>Modified question is - What\'s the difference between A mutex and a "binary" semaphore in "Linux"?</p>\n\n<p>Ans: Following are the differences –\ni) Scope – The scope of mutex is within a process address space which has created it and is used for synchronization of threads. Whereas semaphore can be used across process space and hence it can be used for interprocess synchronization.</p>\n\n<p>ii) Mutex is lightweight and faster than semaphore. Futex is even faster.</p>\n\n<p>iii) Mutex can be acquired by same thread successfully multiple times with condition that it should release it same number of times. Other thread trying to acquire will block. Whereas in case of semaphore if same process tries to acquire it again it blocks as it can be acquired only once.</p>\n'}, {'answer_id': 3517129, 'author': 'jilles', 'author_id': 298656, 'author_profile': 'https://Stackoverflow.com/users/298656', 'pm_score': 2, 'selected': False, 'text': '<p>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. Semaphores may provide more fairness, or fairness can be forced using several condition variables.</p>\n'}, {'answer_id': 5212270, 'author': 'Charan', 'author_id': 477081, 'author_profile': 'https://Stackoverflow.com/users/477081', 'pm_score': 3, 'selected': False, 'text': '<p>A <em>Mutex</em> controls access to a single shared resource. It provides operations to <em>acquire()</em> access to that resource and <em>release()</em> it when done.</p>\n\n<p>A <em>Semaphore</em> controls access to a shared pool of resources. It provides operations to <em>Wait()</em> until one of the resources in the pool becomes available, and <em>Signal()</em> when it is given back to the pool.</p>\n\n<p>When number of resources a Semaphore protects is greater than 1, it is called a <em>Counting Semaphore</em>. When it controls one resource, it is called a <em>Boolean Semaphore</em>. A boolean semaphore is equivalent to a mutex.</p>\n\n<p>Thus a Semaphore is a higher level abstraction than Mutex. A Mutex can be implemented using a Semaphore but not the other way around.</p>\n'}, {'answer_id': 9410398, 'author': 'ajay bidari', 'author_id': 979786, 'author_profile': 'https://Stackoverflow.com/users/979786', 'pm_score': 2, 'selected': False, 'text': '<p>In windows the difference is as below.\n<strong>MUTEX:</strong> process which successfully executes <strong>wait</strong> has to execute a <strong>signal</strong> and vice versa. <strong>BINARY SEMAPHORES:</strong> Different processes can execute <strong>wait</strong> or <strong>signal</strong> operation on a semaphore.</p>\n'}, {'answer_id': 9532228, 'author': 'laksbv', 'author_id': 1228058, 'author_profile': 'https://Stackoverflow.com/users/1228058', 'pm_score': 1, 'selected': False, 'text': '<p>Mutexes have ownership,  unlike  semaphores.   Although  any thread,  within  the  scope  of a mutex, can get an unlocked mutex and lock access to the same critical section of  code,<em>only the thread that locked a mutex <strong>should</strong> unlock it</em>.</p>\n'}, {'answer_id': 13559646, 'author': 'user1852497', 'author_id': 1852497, 'author_profile': 'https://Stackoverflow.com/users/1852497', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.geeksforgeeks.org/archives/9102" rel="nofollow">http://www.geeksforgeeks.org/archives/9102</a>  discusses in details.</p>\n\n<p><code>Mutex</code> is locking mechanism used to synchronize access to a resource.\n<code>Semaphore</code> is signaling mechanism. </p>\n\n<p>Its up to to programmer if he/she wants to use  binary semaphore in place of mutex.</p>\n'}, {'answer_id': 13824078, 'author': 'paxi', 'author_id': 1895252, 'author_profile': 'https://Stackoverflow.com/users/1895252', 'pm_score': 3, 'selected': False, 'text': '<p>You obviously use mutex to lock a data in one thread getting accessed by another thread at the same time.  Assume that you have just called <code>lock()</code> and in the process of accessing data.  This means that you don’t expect any other thread (or another instance of the same thread-code) to access the same data locked by the same mutex.  That is, if it is the same thread-code getting executed on a different thread instance, hits the lock, then the <code>lock()</code> should block the control flow there.  This applies to a thread that uses a different thread-code, which is also accessing the same data and which is also locked by the same mutex.  In this case,  you are still in the process of accessing the data and you may take, say, another 15 secs to reach the mutex unlock (so that the other thread that is getting blocked in mutex lock would unblock and would allow the control to access the data). Do you at any cost allow yet another thread to just unlock the same mutex, and in turn, allow the thread that is already waiting (blocking) in the mutex lock to unblock and access the data?  Hope you got what I am saying here?\nAs per, agreed upon universal definition!,  </p>\n\n<ul>\n<li>with “mutex” this can’t happen.  No other thread can unlock the lock\nin your thread</li>\n<li>with “binary-semaphore” this can happen. Any other thread can unlock\nthe lock in your thread</li>\n</ul>\n\n<p>So, if you are very particular about using binary-semaphore instead of mutex, then you should be very careful in “scoping” the locks and unlocks. I mean that every control-flow that hits every lock should hit an unlock call, also there shouldn’t be any “first unlock”, rather it should be always “first lock”.</p>\n'}, {'answer_id': 15494351, 'author': 'mannnnerd', 'author_id': 1926158, 'author_profile': 'https://Stackoverflow.com/users/1926158', 'pm_score': 2, 'selected': False, 'text': "<p>Mutex is used to protect the sensitive code and data, semaphore is used to synchronization.You also can have practical use with protect the sensitive code, but there might be a risk that release the protection by the other thread by operation V.So The main difference between bi-semaphore and mutex is the ownership.For instance by toilet , Mutex is like that one can enter the toilet and lock the door, no one else can enter until the man get out, bi-semaphore is like that one can  enter the toilet and lock the door, but someone else could enter by asking the administrator to open the door, it's ridiculous.</p>\n"}, {'answer_id': 16616869, 'author': 'Jamshad Ahmad', 'author_id': 2395315, 'author_profile': 'https://Stackoverflow.com/users/2395315', 'pm_score': 4, 'selected': False, 'text': '<p>Mutex are used for " Locking Mechanisms ". one process at a time can use a shared resource</p>\n\n<p>whereas</p>\n\n<p>Semaphores are used for " Signaling Mechanisms " \nlike "I am done , now can continue"</p>\n'}, {'answer_id': 18200546, 'author': 'Raghav Navada', 'author_id': 612581, 'author_profile': 'https://Stackoverflow.com/users/612581', 'pm_score': 2, 'selected': False, 'text': '<p>The concept was clear to me after going over above posts. But there were some lingering questions. So, I wrote this small piece of code. </p>\n\n<p>When we try to give a semaphore without taking it, it goes through. But, when you try to give a mutex without taking it, it fails. I tested this on a Windows platform. Enable USE_MUTEX to run the same code using a MUTEX.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n#define xUSE_MUTEX 1\n#define MAX_SEM_COUNT 1\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam );\nDWORD WINAPI Thread_no_2( LPVOID lpParam );\n\nHANDLE Handle_Of_Thread_1 = 0;\nHANDLE Handle_Of_Thread_2 = 0;\nint Data_Of_Thread_1 = 1;\nint Data_Of_Thread_2 = 2;\nHANDLE ghMutex = NULL;\nHANDLE ghSemaphore = NULL;\n\n\nint main(void)\n{\n\n#ifdef USE_MUTEX\n    ghMutex = CreateMutex( NULL, FALSE, NULL);\n    if (ghMutex  == NULL) \n    {\n        printf("CreateMutex error: %d\\n", GetLastError());\n        return 1;\n    }\n#else\n    // Create a semaphore with initial and max counts of MAX_SEM_COUNT\n    ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);\n    if (ghSemaphore == NULL) \n    {\n        printf("CreateSemaphore error: %d\\n", GetLastError());\n        return 1;\n    }\n#endif\n    // Create thread 1.\n    Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &amp;Data_Of_Thread_1, 0, NULL);  \n    if ( Handle_Of_Thread_1 == NULL)\n    {\n        printf("Create first thread problem \\n");\n        return 1;\n    }\n\n    /* sleep for 5 seconds **/\n    Sleep(5 * 1000);\n\n    /*Create thread 2 */\n    Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &amp;Data_Of_Thread_2, 0, NULL);  \n    if ( Handle_Of_Thread_2 == NULL)\n    {\n        printf("Create second thread problem \\n");\n        return 1;\n    }\n\n    // Sleep for 20 seconds\n    Sleep(20 * 1000);\n\n    printf("Out of the program \\n");\n    return 0;\n}\n\n\nint my_critical_section_code(HANDLE thread_handle)\n{\n\n#ifdef USE_MUTEX\n    if(thread_handle == Handle_Of_Thread_1)\n    {\n        /* get the lock */\n        WaitForSingleObject(ghMutex, INFINITE);\n        printf("Thread 1 holding the mutex \\n");\n    }\n#else\n    /* get the semaphore */\n    if(thread_handle == Handle_Of_Thread_1)\n    {\n        WaitForSingleObject(ghSemaphore, INFINITE);\n        printf("Thread 1 holding semaphore \\n");\n    }\n#endif\n\n    if(thread_handle == Handle_Of_Thread_1)\n    {\n        /* sleep for 10 seconds */\n        Sleep(10 * 1000);\n#ifdef USE_MUTEX\n        printf("Thread 1 about to release mutex \\n");\n#else\n        printf("Thread 1 about to release semaphore \\n");\n#endif\n    }\n    else\n    {\n        /* sleep for 3 secconds */\n        Sleep(3 * 1000);\n    }\n\n#ifdef USE_MUTEX\n    /* release the lock*/\n    if(!ReleaseMutex(ghMutex))\n    {\n        printf("Release Mutex error in thread %d: error # %d\\n", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());\n    }\n#else\n    if (!ReleaseSemaphore(ghSemaphore,1,NULL) )      \n    {\n        printf("ReleaseSemaphore error in thread %d: error # %d\\n",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());\n    }\n#endif\n\n    return 0;\n}\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam ) \n{ \n    my_critical_section_code(Handle_Of_Thread_1);\n    return 0;\n}\n\n\nDWORD WINAPI Thread_no_2( LPVOID lpParam ) \n{\n    my_critical_section_code(Handle_Of_Thread_2);\n    return 0;\n}\n</code></pre>\n\n<p>The very fact that semaphore lets you signal "it is done using a resource", even though it never owned the resource, makes me think there is a very loose coupling between owning and signaling in the case of semaphores. </p>\n'}, {'answer_id': 20113248, 'author': 'Hemant', 'author_id': 1302408, 'author_profile': 'https://Stackoverflow.com/users/1302408', 'pm_score': 7, 'selected': False, 'text': '<p>Since none of the above answer clears the confusion, here is one which cleared my confusion.</p>\n\n<blockquote>\n  <p>Strictly speaking, <strong>a mutex is a locking mechanism</strong> used to\n  synchronize access to a resource. Only one task (can be a thread or\n  process based on OS abstraction) can acquire the mutex. It means there\n  will be ownership associated with mutex, and only the owner can\n  release the lock (mutex).</p>\n  \n  <p><strong>Semaphore is signaling mechanism</strong> (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as\n  one task) on your mobile and at the same time your friend called you,\n  an interrupt will be triggered upon which an interrupt service routine\n  (ISR) will signal the call processing task to wakeup.</p>\n</blockquote>\n\n<p>Source: <a href="http://www.geeksforgeeks.org/mutex-vs-semaphore/" rel="noreferrer">http://www.geeksforgeeks.org/mutex-vs-semaphore/</a></p>\n'}, {'answer_id': 23944923, 'author': 'Saurabh Sinha', 'author_id': 3252237, 'author_profile': 'https://Stackoverflow.com/users/3252237', 'pm_score': 4, 'selected': False, 'text': '<p>Myth:</p>\n\n<p>Couple of article says that "binary semaphore and mutex are same" or "Semaphore with value 1 is mutex" but the basic difference is Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread</p>\n\n<p>Key Points:</p>\n\n<p>•A thread can acquire more than one lock (Mutex).</p>\n\n<p>•A mutex can be locked more than once only if its a recursive mutex, here lock and unlock for mutex should be same</p>\n\n<p>•If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. </p>\n\n<p>•Binary semaphore and mutex are similar but not same.</p>\n\n<p>•Mutex is costly operation due to protection protocols associated with it.</p>\n\n<p>•Main aim of mutex is achieve atomic access or lock on resource</p>\n'}, {'answer_id': 25469033, 'author': 'Praveen_Shukla', 'author_id': 3719105, 'author_profile': 'https://Stackoverflow.com/users/3719105', 'pm_score': 4, 'selected': False, 'text': '<p>Though mutex &amp; semaphores are used as synchronization primitives ,there is a big difference between them.\nIn the case of mutex, only the thread that locked or acquired the mutex can unlock it.\nIn the case of a semaphore, a thread waiting on a semaphore can be signaled by a different thread.\nSome operating system supports using mutex &amp; semaphores between process. Typically usage is creating in shared memory.</p>\n'}, {'answer_id': 29345098, 'author': 'buddy', 'author_id': 103465, 'author_profile': 'https://Stackoverflow.com/users/103465', 'pm_score': 3, 'selected': False, 'text': '<p>Diff between Binary Semaphore and Mutex:\nOWNERSHIP:\n<strong>Semaphores can be signalled (posted) even from a non current owner. It means you can simply post from any other thread, though you are not the owner.</strong></p>\n\n<p>Semaphore is a public property in process, It can be simply posted by a non owner thread.\nPlease Mark this difference in BOLD letters, it mean a lot. </p>\n'}, {'answer_id': 33154919, 'author': 'Neeraj Sh', 'author_id': 5450768, 'author_profile': 'https://Stackoverflow.com/users/5450768', 'pm_score': 0, 'selected': False, 'text': "<p>Mutex and binary semaphore are both of the same usage, but in reality, they are different.</p>\n\n<p>In case of mutex, only the thread which have locked it can unlock it. If any other thread comes to lock it, it will wait. </p>\n\n<p>In case of semaphone, that's not the case. Semaphore is not tied up with a particular thread ID.</p>\n"}, {'answer_id': 34494207, 'author': 'Rahul Yadav', 'author_id': 4037532, 'author_profile': 'https://Stackoverflow.com/users/4037532', 'pm_score': -1, 'selected': False, 'text': '<p>Almost all of the above said it right. Let me also try my bit to clarify if somebody still has a doubt.</p>\n\n<ul>\n<li>Mutex -> used for serialization</li>\n<li>Semaphore-> synchronization.</li>\n</ul>\n\n<p>Purpose of both are different however, same functionality could be achieved through both of them with careful programming.</p>\n\n<p>Standard Example-> producer consumer problem.</p>\n\n<pre><code>initial value of SemaVar=0\n\nProducer                           Consumer\n---                                SemaWait()-&gt;decrement SemaVar   \nproduce data\n---\nSemaSignal SemaVar or SemaVar++  ---&gt;consumer unblocks as SemVar is 1 now.\n</code></pre>\n\n<p>Hope I could clarify.</p>\n'}, {'answer_id': 35305718, 'author': 'Dom045', 'author_id': 830514, 'author_profile': 'https://Stackoverflow.com/users/830514', 'pm_score': 1, 'selected': False, 'text': '<p>As many folks here have mentioned, a mutex is used to protect a critical piece of code (AKA critical section.) You will acquire the mutex (lock), enter critical section, and release mutex (unlock) <strong>all in the same thread</strong>.</p>\n\n<p>While using a semaphore, you can make a thread wait on a semaphore (say thread A), until another thread (say thread B)completes whatever task, and then sets the Semaphore for thread A to stop the wait, and continue its task.</p>\n'}, {'answer_id': 38391937, 'author': 'Adi06411', 'author_id': 6521452, 'author_profile': 'https://Stackoverflow.com/users/6521452', 'pm_score': 2, 'selected': False, 'text': '<p>While a binary semaphore may be used as a mutex, a mutex is a more specific use-case, in that only the process that locked the mutex is supposed to unlock it. This ownership constraint makes it possible to provide protection against:</p>\n\n<ul>\n<li>Accidental release</li>\n<li>Recursive Deadlock</li>\n<li>Task Death Deadlock</li>\n</ul>\n\n<p>These constraints are not always present because they degrade the speed. During the development of your code, you can enable these checks  temporarily. </p>\n\n<p>e.g. you can enable Error check attribute in your mutex. Error checking mutexes return <code>EDEADLK</code> if you try to lock the same one twice and <code>EPERM</code> if you unlock a mutex that isn\'t yours.</p>\n\n<pre><code>pthread_mutex_t mutex;\npthread_mutexattr_t attr;\npthread_mutexattr_init (&amp;attr);\npthread_mutexattr_settype (&amp;attr, PTHREAD_MUTEX_ERRORCHECK_NP);\npthread_mutex_init (&amp;mutex, &amp;attr);\n</code></pre>\n\n<p>Once initialised we can place these checks in our code like this:</p>\n\n<pre><code>if(pthread_mutex_unlock(&amp;mutex)==EPERM)\n printf("Unlock failed:Mutex not owned by this thread\\n");\n</code></pre>\n'}, {'answer_id': 45533202, 'author': 'Sumit Naik', 'author_id': 4590926, 'author_profile': 'https://Stackoverflow.com/users/4590926', 'pm_score': 4, 'selected': False, 'text': '<p>Mutex: Suppose we have critical section thread T1 wants to access it then it follows below steps.\nT1:</p>\n\n<ol>\n<li>Lock</li>\n<li>Use Critical Section</li>\n<li>Unlock</li>\n</ol>\n\n<p>Binary semaphore: It works based on signaling wait and signal.\nwait(s) decrease "s" value by one usually "s" value is initialize with value "1",\nsignal(s) increases "s" value by one. if "s" value is 1 means no one is using critical section, when value is 0 means critical section is in use.\nsuppose thread T2 is using critical section then it follows below steps.\nT2 : </p>\n\n<ol>\n<li>wait(s)//initially s value is one after calling wait it\'s value decreased by one i.e 0</li>\n<li>Use critical section</li>\n<li>signal(s) // now s value is increased and it become 1</li>\n</ol>\n\n<p>Main difference between Mutex and Binary semaphore is in Mutext if thread lock the critical section then it has to unlock critical section no other thread can unlock it, but in case of Binary semaphore if one thread locks critical section using wait(s) function then value of s become "0" and no one can access it until value of "s" become 1 but suppose some other thread calls signal(s) then value of "s" become 1 and it allows other function to use critical section.\nhence in Binary semaphore thread doesn\'t have ownership.</p>\n'}, {'answer_id': 56268218, 'author': 'ilias iliadis', 'author_id': 2362556, 'author_profile': 'https://Stackoverflow.com/users/2362556', 'pm_score': -1, 'selected': False, 'text': '<p>"binary semaphore" is a programming language circumvent to use a «semaphore» like «mutex». Apparently there are two very big differences:</p>\n\n<ol>\n<li><p>The way you call each one of them.</p></li>\n<li><p>The maximum length of the "identifier".</p></li>\n</ol>\n'}, {'answer_id': 57661994, 'author': 'kjohri', 'author_id': 1518661, 'author_profile': 'https://Stackoverflow.com/users/1518661', 'pm_score': 0, 'selected': False, 'text': '<p>The basic issue is concurrency. There is more than one flow of control. Think about two processes using a shared memory. Now only one process can access the shared memory at a time. If more than one process accesses the shared memory at a time, the contents of shared memory would get corrupted. It is like a railroad track. Only one train can run on it, else there would be an accident.So there is a signalling mechanism, which a driver checks. If the signal is green, the train can go and if it is red it has to wait to use the track. Similarly in case of shared memory, there is a binary semaphore. If the semaphore is 1, a process acquires it (makes it 0) and goes ahead and accesses it. If the semaphore is 0, the process waits. The functionality the binary semaphore has to provide is mutual exclusion (or mutex, in short) so that only one of the many concurrent entities (process or thread) mutually excludes others. It is a plus that we have counting semaphores, which help in synchronizing multiple instances of a resource.</p>\n\n<p>Mutual exclusion is the basic functionality provided by semaphores. Now in the context of threads, we might have a different name and syntax for it. But the underlying concept is the same: how to keep integrity of code and data in concurrent programming. In my opinion, things like ownership, and associated checks are refinements provided by implementations.</p>\n'}, {'answer_id': 57809820, 'author': 'Ganesh Chowdhary Sadanala', 'author_id': 8706759, 'author_profile': 'https://Stackoverflow.com/users/8706759', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Best Solution</strong></p>\n\n<p>The only difference is <br/></p>\n\n<p>1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.<br/></p>\n\n<p>2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.</p>\n'}, {'answer_id': 59246656, 'author': 'Vijay Panchal', 'author_id': 2185004, 'author_profile': 'https://Stackoverflow.com/users/2185004', 'pm_score': 1, 'selected': False, 'text': '<p><strong>MUTEX</strong></p>\n\n<p>Until recently, the only sleeping lock in the kernel was the semaphore. Most users of semaphores instantiated a semaphore with a count of one and treated them as a mutual exclusion lock—a sleeping version of the spin-lock. Unfortunately, semaphores are rather generic and do not impose any usage constraints. This makes them useful for managing exclusive access in obscure situations, such as complicated dances between the kernel and userspace. But it also means that simpler locking is harder to do, and the lack of enforced rules makes any sort of automated debugging or constraint enforcement impossible. Seeking a simpler sleeping lock, the kernel developers introduced the mutex.Yes, as you are now accustomed to, that is a confusing name. Let’s clarify.The term “mutex” is a generic name to refer to any sleeping lock that enforces mutual exclusion, such as a semaphore with a usage count of one. In recent Linux kernels, the proper noun “mutex” is now also a specific type of sleeping lock that implements mutual exclusion.That is, a mutex is a mutex.</p>\n\n<p>The simplicity and efficiency of the mutex come from the additional constraints it imposes on its users over and above what the semaphore requires. Unlike a semaphore, which implements the most basic of behaviour in accordance with Dijkstra’s original design, the mutex has a stricter, narrower use case:\nn Only one task can hold the mutex at a time. That is, the usage count on a mutex is always one. </p>\n\n<ol>\n<li>Whoever locked a mutex must unlock it. That is, you cannot lock a mutex in one\ncontext and then unlock it in another. This means that the mutex isn’t suitable for more complicated synchronizations between kernel and user-space. Most use cases,\nhowever, cleanly lock and unlock from the same context.</li>\n<li>Recursive locks and unlocks are not allowed. That is, you cannot recursively acquire the same mutex, and you cannot unlock an unlocked mutex.</li>\n<li>A process cannot exit while holding a mutex.</li>\n<li>A mutex cannot be acquired by an interrupt handler or bottom half, even with\nmutex_trylock().</li>\n<li>A mutex can be managed only via the official API: It must be initialized via the methods described in this section and cannot be copied, hand initialized, or reinitialized.</li>\n</ol>\n\n<p>[1] Linux Kernel Development, Third Edition Robert Love</p>\n'}, {'answer_id': 60917006, 'author': 'Mrinal Verma', 'author_id': 7363183, 'author_profile': 'https://Stackoverflow.com/users/7363183', 'pm_score': 2, 'selected': False, 'text': '<p>I think most of the answers here were confusing especially those saying that mutex can be released only by the process that holds it but semaphore can be signaled by ay process. The above line is kind of vague in terms of semaphore. To understand we should know that there are two kinds of semaphore one is called counting semaphore and the other is called a binary semaphore. In counting semaphore handles access to n number of resources where n can be defined before the use. Each semaphore has a count variable, which keeps the count of the number of resources in use, initially, it is set to n. Each process that wishes to uses a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a release() operation (incrementing the count). When the count becomes 0, all the resources are being used. After that, the process waits until the count becomes more than 0. Now here is the catch only the process that holds the resource can increase the count no other process can increase the count only the processes holding a resource can increase the count and the process waiting for the semaphore again checks and when it sees the resource available it decreases the count again. So in terms of binary semaphore, only the process holding the semaphore can increase the count, and count remains zero until it stops using the semaphore and increases the count and other process gets the chance to access the semaphore.</p>\n\n<p>The main difference between binary semaphore and mutex is that semaphore is a signaling mechanism and mutex is a locking mechanism, but binary semaphore seems to function like mutex that creates confusion, but both are different concepts suitable for a different kinds of work.</p>\n'}, {'answer_id': 65410727, 'author': 'Puttaraju', 'author_id': 442992, 'author_profile': 'https://Stackoverflow.com/users/442992', 'pm_score': -1, 'selected': False, 'text': "<p>You can clearly remember difference by this:</p>\n<ol>\n<li><p>Mutex lock : is for protecting critical region,\nMutex can't be used across processes, only used in single process</p>\n</li>\n<li><p>Semaphore: is for signalling availability of a resource.\nSemaphore can be used both across processes and across processes.</p>\n</li>\n</ol>\n"}, {'answer_id': 67110016, 'author': 'DataCrusade1999', 'author_id': 13128057, 'author_profile': 'https://Stackoverflow.com/users/13128057', 'pm_score': 0, 'selected': False, 'text': '<p>Mutex is a Criteria(Out of 4) that any algorithm that intends to solve the Critical Section Problem must follow whereas binary semaphore in itself is a variable that can take values 0 and 1.</p>\n'}, {'answer_id': 73937642, 'author': 'TonyParker', 'author_id': 3964247, 'author_profile': 'https://Stackoverflow.com/users/3964247', 'pm_score': 0, 'selected': False, 'text': '<ul>\n<li>Mutex uses a locking mechanism i.e. if a process wants to use a\nresource then it locks the resource, uses it and then release it. But\non the other hand, semaphore uses a signalling mechanism where wait()\nand signal() methods are used to show if a process is releasing a\nresource or taking a resource.</li>\n<li>A mutex is an object but semaphore is an integer variable.</li>\n<li>In semaphore, we have wait() and signal() functions. But in mutex,\nthere is no such function.</li>\n<li>A mutex object allows multiple process threads to access a single\nshared resource but only one at a time. On the other hand, semaphore\nallows multiple process threads to access the finite instance of the\nresource until available.</li>\n<li>In mutex, the lock can be acquired and released by the same process\nat a time. But the value of the semaphore variable can be modified by\nany process that needs some resource but only one process can change\nthe value at a time.</li>\n</ul>\n<p>A useful read, I learned and copied from <a href="https://afteracademy.com/blog/difference-between-mutex-and-semaphore-in-operating-system" rel="nofollow noreferrer">here</a></p>\n'}]
['https://Stackoverflow.com/questions/62814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7086/']