互斥是一种编程概念,经常用于解决多线程问题。我对社区的问题是:
什么是互斥锁,如何使用它?
互斥是一种编程概念,经常用于解决多线程问题。我对社区的问题是:
什么是互斥锁,如何使用它?
当前回答
互斥锁是一个互斥标志。它充当了一段代码的门卫,允许一个线程进入,并阻止对所有其他线程的访问。这样可以确保被控制的代码一次只被一个线程访问。只要确保在完成后释放互斥锁即可。:)
其他回答
互斥:互斥是互斥的意思。这意味着在给定的时间内,只有一个进程/线程可以进入临界区。在并发编程中,多个线程/进程更新共享资源(任何变量,共享内存等)可能会导致一些意想不到的结果。(因为结果取决于哪个线程/进程获得了第一次访问)。
为了避免这种意想不到的结果,我们需要一些同步机制,以确保一次只有一个线程/进程可以访问这样的资源。
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。
这确保没有两个进程/线程可以同时访问临界区。
这里有一些很好的答案,这里有另一个很好的类比来解释互斥是什么:
考虑一下带钥匙的单人厕所。当有人进来时,他们拿着钥匙,厕所就有人了。如果有人要上厕所,他们需要排队。上完厕所的人把钥匙交给下一个排队的人。说得通,对吧?
将故事中的厕所转换为共享资源和互斥锁的密钥。带上厕所的钥匙(买一把锁)你就可以使用它了。如果没有钥匙(锁上了),你就得等。当钥匙被人归还(打开锁)时,你现在就可以自由地获得它了。
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主题非常值得一读。
互斥锁在需要跨多个进程强制独占访问某个资源的情况下非常有用,而常规锁则没有帮助,因为它只能跨线程工作。
在c#中,常用的互斥量是Monitor。类型是'System.Threading.Monitor'。它也可以通过'lock(Object)'语句隐式使用。它的一个使用示例是在构造Singleton类时。
private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
lock(instanceLock)
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
使用私有锁对象的lock语句创建了一个临界区。要求每个线程等待前一个线程完成。第一个线程将进入该节并初始化实例。第二个线程将等待,进入该节,并获得初始化的实例。
静态成员的任何类型的同步都可以类似地使用lock语句。