뮤텍스 란 무엇입니까?
뮤텍스는 다중 스레딩 문제를 해결하는 데 자주 사용되는 프로그래밍 개념입니다. 커뮤니티에 대한 나의 질문 :
뮤텍스 란 무엇이며 어떻게 사용합니까?
직장에서 열띤 토론을 할 때 나는 그런 경우에만 책상에 두는 고무 치킨을 사용합니다. 닭을 안고있는 사람 만이 말을 할 수 있습니다. 닭을 잡지 않으면 말할 수 없습니다. 닭고기를 원한다고 표시하고 말하기 전에 얻을 때까지 기다릴 수 있습니다. 말이 끝나면 다음 사람에게 닭을 건네 줄 중재자에게 닭을 돌려 줄 수 있습니다. 이렇게하면 사람들이 서로에 대해 말하지 않고 자신 만의 대화 공간을 확보 할 수 있습니다.
치킨을 뮤텍스로, 사람을 스레드로 바꾸면 기본적으로 뮤텍스의 개념이 있습니다.
물론 고무 뮤텍스와 같은 것은 없습니다. 고무 치킨 만. 내 고양이는 한때 고무 마우스를 가지고 있었지만 그것을 먹었습니다.
물론 고무 치킨을 사용하기 전에 한 방에 실제로 5 명이 필요한지 스스로에게 물어볼 필요가 있으며 한 사람이 혼자서 모든 작업을하는 것이 더 쉬울 수는 없을 것입니다. 사실, 이것은 비유를 확장하는 것일 뿐이지 만 아이디어를 얻습니다.
Mutex는 상호 배타적 인 플래그입니다. 하나의 스레드를 허용하고 다른 모든 스레드에 대한 액세스를 차단하는 코드 섹션에 대한 게이트 키퍼 역할을합니다. 이렇게하면 제어되는 코드가 한 번에 하나의 스레드에만 적중됩니다. 완료되면 뮤텍스를 해제하십시오. :)
상호 배제. 여기에 Wikipedia 항목이 있습니다.
http://en.wikipedia.org/wiki/Mutual_exclusion
뮤텍스의 요점은 두 스레드를 동기화하는 것입니다. 단일 리소스에 액세스하려는 두 개의 스레드가있는 경우 일반적인 패턴은 코드를 입력하기 전에 뮤텍스를 설정하기 위해 액세스를 시도하는 첫 번째 코드 블록을 갖는 것입니다. 두 번째 코드 블록이 액세스를 시도하면 뮤텍스가 설정되었음을 확인하고 첫 번째 코드 블록이 완료 될 때까지 기다린 다음 (뮤텍스 설정 해제) 계속합니다.
이를 수행하는 방법에 대한 구체적인 세부 사항은 프로그래밍 언어에 따라 크게 다릅니다.
다중 스레드 응용 프로그램이있는 경우 다른 스레드는 때때로 변수 또는 유사한 것과 같은 공통 리소스를 공유합니다. 이 공유 소스는 동시에 액세스 할 수없는 경우가 많으므로 한 번에 하나의 스레드 만 해당 리소스를 사용하도록 구성해야합니다.
이 개념은 "상호 배제"(짧은 뮤텍스)라고하며 해당 리소스 등을 사용하여 해당 영역 내에서 하나의 스레드 만 허용되도록하는 방법입니다.
사용 방법은 언어별로 다르지만 운영 체제 뮤텍스를 기반으로하는 경우가 많습니다.
예를 들어 함수형 프로그래밍 (Haskell, ML이 좋은 예)과 같은 패러다임으로 인해 일부 언어에는이 구조가 필요하지 않습니다.
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;
}
}
개인 잠금 개체를 사용하는 잠금 문은 중요 섹션을 만듭니다. 이전 스레드가 완료 될 때까지 각 스레드를 기다려야합니다. 첫 번째 스레드는 섹션에 들어가 인스턴스를 초기화합니다. 두 번째 스레드는 대기하고 섹션으로 들어가 초기화 된 인스턴스를 가져옵니다.
정적 멤버의 모든 동기화는 잠금 문을 비슷하게 사용할 수 있습니다.
뮤텍스 는 무엇입니까 ?
스핀 록 (spinlock)이라고도하는 뮤텍스 (사실 뮤텍스라는 용어는 상호 배제의 약자)는 중요한 영역을 보호하여 경쟁 조건을 방지하는 데 사용되는 가장 간단한 동기화 도구입니다. 즉, 스레드는 임계 섹션에 들어가기 전에 잠금을 획득해야합니다 (중요 섹션에서는 다중 스레드가 공통 변수 공유, 테이블 업데이트, 파일 쓰기 등). 임계 섹션을 떠날 때 잠금을 해제합니다.
경쟁 조건 이란 무엇입니까 ?
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 "racing" to access/change the data.
Real life example:
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
Usage in C#:
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.
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
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.
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.
The MUTEX topic in this pdf file link is really worth reading.
There are some great answers here, here is another great analogy for explaining what mutex is:
Consider single toilet with a key. When someone enters, they take the key and the toilet is occupied. If someone else needs to use the toilet, they need to wait in a queue. When the person in the toilet is done, they pass the key to the next person in queue. Make sense, right?
Convert the toilet in the story to a shared resource, and the key to a mutex. 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 (release the lock) you're free to acquire it now.
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.
참고URL : https://stackoverflow.com/questions/34524/what-is-a-mutex
'Programing' 카테고리의 다른 글
중첩 된 JavaScript 개체 키의 존재 여부 테스트 (0) | 2020.10.03 |
---|---|
텍스트 JavaScript에서 HTML 제거 (0) | 2020.10.03 |
Chrome의 코드에서 JavaScript 중단 점을 설정하는 방법은 무엇입니까? (0) | 2020.10.02 |
JavaScript 개체의 속성을 어떻게 열거합니까? (0) | 2020.10.02 |
페이지로드 후 JavaScript를 실행하는 방법은 무엇입니까? (0) | 2020.10.02 |