programing tip

언제 뮤텍스를 사용해야하고 언제 세마포어를 사용해야합니까?

itbloger 2020. 8. 13. 07:58
반응형

언제 뮤텍스를 사용해야하고 언제 세마포어를 사용해야합니까?


언제 뮤텍스를 사용해야하고 언제 세마포어를 사용해야합니까?


다음은 언제 무엇을 사용해야하는지 기억하는 방법입니다.

세마포어 : 다른 스레드가 깨어나도록 지시 할 때까지 (스레드) 잠자기를 원할 때 세마포어를 사용합니다. 세마포어 '다운'은 한 스레드 (생산자)에서 발생하고 세마포어 '업'(동일한 세마포어)은 다른 스레드 (소비자)에서 발생합니다. 소비자 스레드는 버퍼 슬롯이 비어있는시기를 알 수 있습니다.

뮤텍스 : (스레드) 다른 스레드에서 동시에 실행해서는 안되는 코드를 실행하려는 경우 뮤텍스를 사용합니다. 뮤텍스 '다운'은 한 스레드에서 발생하고 뮤텍스 '업' 나중에 동일한 스레드에서 발생 해야합니다 . 예 : 글로벌 연결 목록에서 노드를 삭제하는 경우 노드를 삭제하는 동안 다른 스레드가 포인터를 사용하는 것을 원하지 않습니다. 뮤텍스를 획득하고 노드 삭제 중일 때 다른 스레드가 동일한 뮤텍스를 획득하려고 시도하면 뮤텍스를 해제 할 때까지 휴면 상태가됩니다.

Spinlock : 실제로 뮤텍스를 사용하고 싶지만 스레드가 잠자기 상태가 아닐 때 스핀 락 을 사용합니다. 예 : OS 커널 내의 인터럽트 핸들러는 절대 휴면 상태가 아니어야합니다. 그렇다면 시스템이 정지 / 충돌합니다. 인터럽트 처리기에서 전역 적으로 공유되는 연결 목록에 노드를 삽입해야하는 경우 스핀 락을 획득합니다-노드 삽입-스핀 록 해제.


뮤텍스는 세마포어 와 유사 하지만 한 번에 하나의 로커 만 허용하고 소유권 제한이 세마포어보다 더 엄격 할 수 있는 상호 배제 개체 입니다.

이는 일반 세마포어 (1 개 포함) 및이를 잠근 동일한 스레드에서만 해제 할 수 있어야한다는 요구 사항 (a) 과 동일하다고 생각할 수 있습니다 .

반면에 세마포어는 임의의 개수를 가지며 동시에 많은 로커에 의해 잠길 수 있습니다. 그리고 그것을 주장한 동일한 스레드에 의해 해제되어야한다는 요구 사항이 없을 수도 있습니다 (그러나 그렇지 않다면 할당 된 메모리와 같이 현재 책임이있는 사람을주의 깊게 추적해야합니다).

따라서 리소스 인스턴스 (예 : 3 개의 테이프 드라이브)가있는 경우 개수가 3 인 세마포어를 사용할 수 있습니다. 이것은 테이프 드라이브 중 어떤 것을 가지고 있는지 알려주는 것이 아니라 특정 숫자.

또한 세마포어를 사용하면 단일 로커가 테이프 간 복사와 같이 리소스의 여러 인스턴스를 잠글 수 있습니다. 하나의 리소스 (손상하지 않으려는 메모리 위치)가있는 경우 뮤텍스가 더 적합합니다.

동등한 작업은 다음과 같습니다.

Counting semaphore          Mutual exclusion semaphore
--------------------------  --------------------------
  Claim/decrease (P)                  Lock
  Release/increase (V)                Unlock

곁에 : 세마포어를 주장하고 해제하는 데 사용되는 기괴한 편지에 대해 궁금해 한 적이 있다면 발명가가 네덜란드 사람 이었기 때문입니다. Probeer te verlagen은 시도하고 감소하는 것을 의미하고 verhogen은 증가하는 것을 의미합니다.


(a) ... 또는 세마포어와는 완전히 다른 것으로 생각할 수 있으며, 거의 항상 다른 용도로 사용하면 더 안전 할 수 있습니다.


뮤텍스 카운트 1의 세마포어 가 아니라는 것을 이해하는 것이 매우 중요합니다 !

이것이 바이너리 세마포어 (실제로 카운트 1의 세마포어)와 같은 것이있는 이유입니다.

Mutex와 Binary-Semaphore의 차이점은 소유권 원칙입니다.

뮤텍스는 작업에 의해 획득되므로 동일한 작업에 의해 해제되어야합니다. 이를 통해 이진 세마포어 (우연적 해제, 재귀 교착 상태 및 우선 순위 반전)와 관련된 여러 문제를 해결할 수 있습니다.

주의 사항 : 이러한 문제를 해결하는 방법과 방법은 OS 구현에 달려 있습니다.

뮤텍스는 동일한 작업에 의해 해제되어야하므로 작업 동기화에 적합하지 않습니다. 그러나 조건 변수와 결합하면 모든 종류의 ipc 프리미티브를 구축하기위한 매우 강력한 빌딩 블록을 얻을 수 있습니다.

그래서 내 권장 사항은 : 뮤텍스와 조건 변수 (POSIX pthreads와 같은)를 깨끗하게 구현했다면 이것을 사용하십시오.

해결하려는 문제에 정확히 맞는 경우에만 세마포를 사용하고, 다른 프리미티브를 빌드하지 마십시오 (예 : 세마포에서 rw-locks, 뮤텍스 및 조건 변수 사용).

뮤텍스와 세마포어에 대한 오해가 많이 있습니다. 지금까지 찾은 가장 좋은 설명은이 3 부 문서입니다.

뮤텍스 대 세마포어 – 파트 1 : 세마포어

뮤텍스 대 세마포어 – 파트 2 : 뮤텍스

뮤텍스 대 세마포어 – 파트 3 (마지막 파트) : 상호 배제 문제


@opaxdiablo 대답은 완전히 정확하지만 두 가지 사용 시나리오가 상당히 다르다는 점을 지적하고 싶습니다. 뮤텍스는 코드의 일부가 동시에 실행되지 않도록 보호하는 데 사용되며, 세마포는 한 스레드가 다른 스레드가 실행되도록 신호를 보내는 데 사용됩니다.

/* Task 1 */
pthread_mutex_lock(mutex_thing);
    // Safely use shared resource
pthread_mutex_unlock(mutex_thing);



/* Task 2 */
pthread_mutex_lock(mutex_thing);
   // Safely use shared resource
pthread_mutex_lock(mutex_thing);

세마포어 시나리오는 다릅니다.

/* Task 1 - Producer */
sema_post(&sem);   // Send the signal

/* Task 2 - Consumer */
sema_wait(&sem);   // Wait for signal

See http://www.netrino.com/node/202 for further explanations


See "The Toilet Example" - http://pheatt.emporia.edu/courses/2010/cs557f10/hand07/Mutex%20vs_%20Semaphore.htm:

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library


Trying not to sound zany, but can't help myself.

Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'

(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)

In object terminology we can observe that :

observation.1 Semaphore contains mutex

observation.2 Mutex is not semaphore and semaphore is not mutex.

There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.

There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.

There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.

This is where confusion pours in like monsoon rain.

A semaphore with a counter that can be 0 or 1 is NOT mutex.

Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.

Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.

  1. Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore

  2. Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore

  3. Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)

Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive

Use semaphores, when what you want is exactly provided by it.

If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.

And lastly read a book rather than relying just on SO.


I think the question should be the difference between mutex and binary semaphore.

Mutex = It is a ownership lock mechanism, only the thread who acquire the lock can release the lock.

binary Semaphore = It is more of a signal mechanism, any other higher priority thread if want can signal and take the lock.


Mutex is to protect the shared resource.
Semaphore is to dispatch the threads.

Mutex:
Imagine that there are some tickets to sell. We can simulate a case where many people buy the tickets at the same time: each person is a thread to buy tickets. Obviously we need to use the mutex to protect the tickets because it is the shared resource.


Semaphore:
Imagine that we need to do a calculation as below:

c = a + b;

Also, we need a function geta() to calculate a, a function getb() to calculate b and a function getc() to do the calculation c = a + b.

Obviously, we can't do the c = a + b unless geta() and getb() have been finished.
If the three functions are three threads, we need to dispatch the three threads.

int a, b, c;
void geta()
{
    a = calculatea();
    semaphore_increase();
}

void getb()
{
    b = calculateb();
    semaphore_increase();
}

void getc()
{
    semaphore_decrease();
    semaphore_decrease();
    c = a + b;
}

t1 = thread_create(geta);
t2 = thread_create(getb);
t3 = thread_create(getc);
thread_join(t3);

With the help of the semaphore, the code above can make sure that t3 won't do its job untill t1 and t2 have done their jobs.

In a word, semaphore is to make threads execute as a logicial order whereas mutex is to protect shared resource.
So they are NOT the same thing even if some people always say that mutex is a special semaphore with the initial value 1. You can say like this too but please notice that they are used in different cases. Don't replace one by the other even if you can do that.


All the above answers are of good quality,but this one's just to memorize.The name Mutex is derived from Mutually Exclusive hence you are motivated to think of a mutex lock as Mutual Exclusion between two as in only one at a time,and if I possessed it you can have it only after I release it.On the other hand such case doesn't exist for Semaphore is just like a traffic signal(which the word Semaphore also means).


As was pointed out, a semaphore with a count of one is the same thing as a 'binary' semaphore which is the same thing as a mutex.

The main things I've seen semaphores with a count greater than one used for is producer/consumer situations in which you have a queue of a certain fixed size.

You have two semaphores then. The first semaphore is initially set to be the number of items in the queue and the second semaphore is set to 0. The producer does a P operation on the first semaphore, adds to the queue. and does a V operation on the second. The consumer does a P operation on the second semaphore, removes from the queue, and then does a V operation on the first.

In this way the producer is blocked whenever it fills the queue, and the consumer is blocked whenever the queue is empty.


A mutex is a special case of a semaphore. A semaphore allows several threads to go into the critical section. When creating a semaphore you define how may threads are allowed in the critical section. Of course your code must be able to handle several accesses to this critical section.

참고URL : https://stackoverflow.com/questions/4039899/when-should-we-use-mutex-and-when-should-we-use-semaphore

반응형