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

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

[{'answer_id': 34548, 'author': 'Mats Fredriksson', 'author_id': 2973, 'author_profile': 'https://Stackoverflow.com/users/2973', 'pm_score': 6, 'selected': False, 'text': '<p>When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.</p>\n\n<p>The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.</p>\n\n<p>How to use them is language specific, but is often (if not always) based on a operating system mutex.</p>\n\n<p>Some languages doesn\'t need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).</p>\n'}, {'answer_id': 34551, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Mut</strong>ual <strong>Ex</strong>clusion. <a href="https://en.wikipedia.org/wiki/Mutual_exclusion" rel="noreferrer">Here\'s the Wikipedia entry on it.</a></p>\n<p>The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.</p>\n<p>Specific details of how this is accomplished obviously varies greatly by programming language.</p>\n'}, {'answer_id': 34556, 'author': 'Craig', 'author_id': 2894, 'author_profile': 'https://Stackoverflow.com/users/2894', 'pm_score': 8, 'selected': False, 'text': '<p>A Mutex is a <strong>Mut</strong>ually <strong>ex</strong>clusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controlled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done. :)</p>\n'}, {'answer_id': 34558, 'author': 'Xetius', 'author_id': 274, 'author_profile': 'https://Stackoverflow.com/users/274', 'pm_score': 11, 'selected': False, 'text': "<p>When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions.  The person holding the chicken is the only person who is allowed to talk.  If you don't hold the chicken you cannot speak.  You can only indicate that you want the chicken and wait until you get it before you speak.  Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak.  This ensures that people do not speak over each other, and also have their own space to talk.</p>\n\n<p>Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.</p>\n\n<p>Of course, there is no such thing as a rubber mutex.  Only rubber chicken.  My cats once had a rubber mouse, but they ate it.</p>\n\n<p>Of course, before you use the rubber chicken, you need to ask yourself whether you actually need 5 people in one room and would it not just be easier with one person in the room on their own doing all the work.  Actually, this is just extending the analogy, but you get the idea.</p>\n"}, {'answer_id': 34574, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 5, 'selected': False, 'text': '<p>In C#, the common mutex used is the <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)" rel="noreferrer">Monitor</a>. The type is \'<a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx" rel="noreferrer">System.Threading.Monitor</a>\'. It may also be used implicitly via the \'<a href="http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx" rel="noreferrer">lock(Object)</a>\' statement. One example of its use is when constructing a Singleton class.</p>\n\n<pre class="lang-cs prettyprint-override"><code>private static readonly Object instanceLock = new Object();\nprivate static MySingleton instance;\npublic static MySingleton Instance\n{\n    lock(instanceLock)\n    {\n        if(instance == null)\n        {\n            instance = new MySingleton();\n        }\n        return instance;\n    }\n}\n</code></pre>\n\n<p>The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.</p>\n\n<p>Any sort of synchronization of a static member may use the lock statement similarly.</p>\n'}, {'answer_id': 40305, 'author': '18hrs', 'author_id': 1361, 'author_profile': 'https://Stackoverflow.com/users/1361', 'pm_score': 4, 'selected': False, 'text': "<p>Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.</p>\n"}, {'answer_id': 24449020, 'author': 'user3751012', 'author_id': 3751012, 'author_profile': 'https://Stackoverflow.com/users/3751012', 'pm_score': 4, 'selected': False, 'text': '<p>To understand MUTEX at first you need to know what is "race condition" and then only you will understand why MUTEX is needed. Suppose you have a multi-threading program and you have two threads. Now, you have one job in the job queue. The first thread will check the job queue and after finding the job it will start executing it. The second thread will also check the job queue and find that there is one job in the queue. So, it will also assign the same job pointer. So, now what happens, both the threads are executing the same job. This will cause a segmentation fault. This is the example of a race condition. </p>\n\n<p>The solution to this problem is MUTEX. MUTEX is a kind of lock which locks one thread at a time. If another thread wants to lock it, the thread simply gets blocked. </p>\n\n<p>The MUTEX topic <a href="http://www.advancedlinuxprogramming.com/alp-folder/alp-ch05-ipc.pdf">in this pdf file</a> link is really worth reading.</p>\n'}, {'answer_id': 46642398, 'author': 'Chen A.', 'author_id': 840582, 'author_profile': 'https://Stackoverflow.com/users/840582', 'pm_score': 5, 'selected': False, 'text': "<p>There are some great answers here, here is another great analogy for explaining what <strong>mutex</strong> is:</p>\n\n<p>Consider <strong>single</strong> toilet with a <em>key</em>. When someone enters, they take the key and the toilet is <em>occupied</em>. If someone else needs to use the toilet, they need to wait in a <em>queue</em>. When the person in the toilet is <em>done</em>, they pass the key to the next person in queue. Make sense, right?</p>\n\n<p>Convert the <em>toilet</em> in the story to a <em>shared resource</em>, and the <em>key</em> to a <em>mutex</em>. Taking the key to the toilet (acquire a lock) permits you to use it. If there is no key (the lock is locked) you have to wait. When the key is returned by the person (<em>release the lock</em>) you're free to acquire it now.</p>\n"}, {'answer_id': 51146022, 'author': 'habib', 'author_id': 5559267, 'author_profile': 'https://Stackoverflow.com/users/5559267', 'pm_score': 5, 'selected': False, 'text': '<p><strong>What is a <a href="https://en.wikipedia.org/wiki/Mutual_exclusion" rel="noreferrer">Mutex</a>?</strong></p>\n<p>The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.</p>\n<p><strong>What is a <a href="https://en.wikipedia.org/wiki/Race_condition" rel="noreferrer">Race Condition</a>?</strong></p>\n<p>A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don\'t know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are &quot;racing&quot; to access/change the data.</p>\n<p><strong>Real life example:</strong></p>\n<blockquote>\n<p>When I am having a big heated discussion at work, I use a rubber\nchicken which I keep in my desk for just such occasions. The person\nholding the chicken is the only person who is allowed to talk. If you\ndon\'t hold the chicken you cannot speak. You can only indicate that\nyou want the chicken and wait until you get it before you speak. Once\nyou have finished speaking, you can hand the chicken back to the\nmoderator who will hand it to the next person to speak. This ensures\nthat people do not speak over each other, and also have their own\nspace to talk.</p>\n<p>Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.</p>\n<p>@Xetius</p>\n</blockquote>\n<p><strong>Usage in C#:</strong></p>\n<p>This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.</p>\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Threading;\n\nclass Example\n{\n    // Create a new Mutex. The creating thread does not own the mutex.\n    private static Mutex mut = new Mutex();\n    private const int numIterations = 1;\n    private const int numThreads = 3;\n\n    static void Main()\n    {\n        // Create the threads that will use the protected resource.\n        for(int i = 0; i &lt; numThreads; i++)\n        {\n            Thread newThread = new Thread(new ThreadStart(ThreadProc));\n            newThread.Name = String.Format(&quot;Thread{0}&quot;, i + 1);\n            newThread.Start();\n        }\n\n        // The main thread exits, but the application continues to\n        // run until all foreground threads have exited.\n    }\n\n    private static void ThreadProc()\n    {\n        for(int i = 0; i &lt; numIterations; i++)\n        {\n            UseResource();\n        }\n    }\n\n    // This method represents a resource that must be synchronized\n    // so that only one thread at a time can enter.\n    private static void UseResource()\n    {\n        // Wait until it is safe to enter.\n        Console.WriteLine(&quot;{0} is requesting the mutex&quot;, \n                          Thread.CurrentThread.Name);\n        mut.WaitOne();\n\n        Console.WriteLine(&quot;{0} has entered the protected area&quot;, \n                          Thread.CurrentThread.Name);\n\n        // Place code to access non-reentrant resources here.\n\n        // Simulate some work.\n        Thread.Sleep(500);\n\n        Console.WriteLine(&quot;{0} is leaving the protected area&quot;, \n            Thread.CurrentThread.Name);\n\n        // Release the Mutex.\n        mut.ReleaseMutex();\n        Console.WriteLine(&quot;{0} has released the mutex&quot;, \n            Thread.CurrentThread.Name);\n    }\n}\n// The example displays output like the following:\n//       Thread1 is requesting the mutex\n//       Thread2 is requesting the mutex\n//       Thread1 has entered the protected area\n//       Thread3 is requesting the mutex\n//       Thread1 is leaving the protected area\n//       Thread1 has released the mutex\n//       Thread3 has entered the protected area\n//       Thread3 is leaving the protected area\n//       Thread3 has released the mutex\n//       Thread2 has entered the protected area\n//       Thread2 is leaving the protected area\n//       Thread2 has released the mutex\n</code></pre>\n<p><a href="https://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx" rel="noreferrer">MSDN Reference Mutex</a></p>\n'}, {'answer_id': 59878707, 'author': 'Sandeep_black', 'author_id': 7277468, 'author_profile': 'https://Stackoverflow.com/users/7277468', 'pm_score': 3, 'selected': False, 'text': '<p>Mutex: Mutex stands for <strong>Mut</strong>ual <strong>Ex</strong>clusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).</p>\n<p>In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.</p>\n<p>pthread library provides support for Mutex.</p>\n<pre class="lang-cpp prettyprint-override"><code>typedef union\n{\n  struct __pthread_mutex_s\n  {\n    ***int __lock;***\n    unsigned int __count;\n    int __owner;\n#ifdef __x86_64__\n    unsigned int __nusers;\n#endif\nint __kind;\n#ifdef __x86_64__\n    short __spins;\n    short __elision;\n    __pthread_list_t __list;\n# define __PTHREAD_MUTEX_HAVE_PREV      1\n# define __PTHREAD_SPINS             0, 0\n#else\n    unsigned int __nusers;\n    __extension__ union\n    {\n      struct\n      {\n        short __espins;\n        short __elision;\n# define __spins __elision_data.__espins\n# define __elision __elision_data.__elision\n# define __PTHREAD_SPINS         { 0, 0 }\n      } __elision_data;\n      __pthread_slist_t __list;\n    };\n#endif\n</code></pre>\n<p>This is the structure for mutex data type i.e pthread_mutex_t.\nWhen mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.</p>\n<p>This ensure that no two processes/threads can access the critical section at same time.</p>\n'}]
['https://Stackoverflow.com/questions/34524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931/']