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

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


当前回答

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.

这个问题的解决方案是互斥。互斥锁是一种一次锁定一个线程的锁。如果另一个线程想要锁定它,那么这个线程就会被阻塞。

这个pdf文件链接中的MUTEX主题非常值得一读。

其他回答

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.

这个问题的解决方案是互斥。互斥锁是一种一次锁定一个线程的锁。如果另一个线程想要锁定它,那么这个线程就会被阻塞。

这个pdf文件链接中的MUTEX主题非常值得一读。

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

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

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

由于范式的原因,一些语言不需要这个构造,例如函数式编程(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引用互斥

互斥:互斥是互斥的意思。这意味着在给定的时间内,只有一个进程/线程可以进入临界区。在并发编程中,多个线程/进程更新共享资源(任何变量,共享内存等)可能会导致一些意想不到的结果。(因为结果取决于哪个线程/进程获得了第一次访问)。

为了避免这种意想不到的结果,我们需要一些同步机制,以确保一次只有一个线程/进程可以访问这样的资源。

pthread库提供了对Mutex的支持。

typedef union
{
  struct __pthread_mutex_s
  {
    ***int __lock;***
    unsigned int __count;
    int __owner;
#ifdef __x86_64__
    unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
    short __spins;
    short __elision;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
# define __PTHREAD_SPINS             0, 0
#else
    unsigned int __nusers;
    __extension__ union
    {
      struct
      {
        short __espins;
        short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS         { 0, 0 }
      } __elision_data;
      __pthread_slist_t __list;
    };
#endif

这是互斥锁数据类型的结构,即pthread_mutex_t。 当互斥锁被锁定时,__lock设置为1。当它被解锁时,__lock设置为0。

这确保没有两个进程/线程可以同时访问临界区。

互斥。这是维基百科上的词条。

互斥锁的作用是同步两个线程。当有两个线程试图访问一个资源时,一般的模式是让第一个代码块在进入代码之前尝试访问设置互斥量。当第二个代码块尝试访问时,它看到互斥锁已设置,并等待到第一个代码块完成(并取消互斥锁),然后继续。

如何实现这一点的具体细节显然因编程语言的不同而有很大差异。