互斥是一种编程概念,经常用于解决多线程问题。我对社区的问题是:

什么是互斥锁,如何使用它?


当前回答

这里有一些很好的答案,这里有另一个很好的类比来解释互斥是什么:

考虑一下带钥匙的单人厕所。当有人进来时,他们拿着钥匙,厕所就有人了。如果有人要上厕所,他们需要排队。上完厕所的人把钥匙交给下一个排队的人。说得通,对吧?

将故事中的厕所转换为共享资源和互斥锁的密钥。带上厕所的钥匙(买一把锁)你就可以使用它了。如果没有钥匙(锁上了),你就得等。当钥匙被人归还(打开锁)时,你现在就可以自由地获得它了。

其他回答

当您有一个多线程应用程序时,不同的线程有时会共享一个公共资源,例如变量或类似的资源。这个共享源通常不能同时访问,因此需要一个构造来确保一次只有一个线程在使用该资源。

这个概念被称为“互斥”(简称互斥),是一种确保只有一个线程被允许在该区域内使用该资源等的方法。

如何使用它们是特定于语言的,但通常(如果不是总是)基于操作系统互斥。

由于范式的原因,一些语言不需要这个构造,例如函数式编程(Haskell和ML就是很好的例子)。

什么是互斥锁?

互斥(事实上,互斥这个术语是互斥的缩写)也称为自旋锁,是用于保护关键区域从而防止竞争条件的最简单的同步工具。也就是说,一个线程在进入临界区之前必须获得一个锁(在临界区中,多个线程共享一个公共变量,更新一个表,写一个文件等等),当它离开临界区时释放锁。

什么是竞态条件?

当两个或多个线程可以访问共享数据,并且它们试图同时更改数据时,就会发生竞态条件。因为线程调度算法可以在任何时候在线程之间交换,所以您不知道线程将尝试访问共享数据的顺序。因此,数据更改的结果依赖于线程调度算法,即两个线程都在“竞相”访问/更改数据。

现实生活中的例子:

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. Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex. @Xetius

在c#中的用法:

这个例子展示了如何使用本地互斥对象同步对受保护资源的访问。因为每个调用线程在获得互斥锁的所有权之前都会被阻塞,所以它必须调用ReleaseMutex方法来释放线程的所有权。

using System;
using System.Threading;

class Example
{
    // Create a new Mutex. The creating thread does not own the mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread newThread = new Thread(new ThreadStart(ThreadProc));
            newThread.Name = String.Format("Thread{0}", i + 1);
            newThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void ThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        Console.WriteLine("{0} is requesting the mutex", 
                          Thread.CurrentThread.Name);
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
                          Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area", 
            Thread.CurrentThread.Name);

        // Release the Mutex.
        mut.ReleaseMutex();
        Console.WriteLine("{0} has released the mutex", 
            Thread.CurrentThread.Name);
    }
}
// The example displays output like the following:
//       Thread1 is requesting the mutex
//       Thread2 is requesting the mutex
//       Thread1 has entered the protected area
//       Thread3 is requesting the mutex
//       Thread1 is leaving the protected area
//       Thread1 has released the mutex
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
//       Thread3 has released the mutex
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       Thread2 has released the mutex

MSDN引用互斥

这里有一些很好的答案,这里有另一个很好的类比来解释互斥是什么:

考虑一下带钥匙的单人厕所。当有人进来时,他们拿着钥匙,厕所就有人了。如果有人要上厕所,他们需要排队。上完厕所的人把钥匙交给下一个排队的人。说得通,对吧?

将故事中的厕所转换为共享资源和互斥锁的密钥。带上厕所的钥匙(买一把锁)你就可以使用它了。如果没有钥匙(锁上了),你就得等。当钥匙被人归还(打开锁)时,你现在就可以自由地获得它了。

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.

用互斥对象替换Chicken,用线程替换person,你基本上就有了互斥对象的概念。

当然,不存在橡胶互斥锁这种东西。只有橡皮鸡。我的猫曾经有一只橡皮老鼠,但它们把它吃了。

当然,在你使用橡皮鸡之前,你需要问问自己,你是否真的需要5个人在一个房间里,一个人独自做所有的工作不是更容易吗?实际上,这只是扩展了类比,但你懂的。

互斥锁在需要跨多个进程强制独占访问某个资源的情况下非常有用,而常规锁则没有帮助,因为它只能跨线程工作。