logo

뮤텍스와 세마포어

운영 체제 용어에 따르면 뮤텍스와 세마포어는 동기화 서비스를 제공하는 커널 리소스입니다. 동기화 프리미티브 . 프로세스 동기화는 공유 데이터의 일관성을 유지하는 데 중요한 역할을 합니다. 중요한 섹션 문제를 처리하기 위한 소프트웨어와 하드웨어 솔루션이 모두 제공됩니다. 그러나 중요한 섹션 문제에 대한 하드웨어 솔루션은 구현하기가 매우 어렵습니다. 뮤텍스와 세마포어는 모두 동기화 서비스를 제공하지만 동일하지는 않습니다.

뮤텍스란 무엇입니까?

Mutex는 리소스에 대한 액세스를 동기화하는 상호 배제 개체입니다. 프로그램 시작 시 고유한 이름으로 생성됩니다. 뮤텍스 잠금 메커니즘은 단 하나의 스레드만이 뮤텍스를 획득하고 임계 섹션에 들어갈 수 있도록 보장합니다. 이 스레드는 임계 섹션에서 종료될 때만 뮤텍스를 해제합니다.

뮤텍스와 세마포어

공유 리소스에 대한 액세스를 제어하는 ​​데 사용되는 특별한 유형의 이진 세마포어입니다. 확장된 우선순위 반전 문제를 방지하기 위한 우선순위 상속 메커니즘이 포함되어 있습니다. 이를 통해 현재 우선 순위가 높은 작업을 가능한 한 짧은 시간 동안 차단 상태로 유지할 수 있습니다. 그러나 우선순위 상속은 우선순위 역전을 수정하지 않고 그 효과를 최소화할 뿐입니다.

이는 다음 예제의 도움으로 표시됩니다.

 wait (mutex); ..... Critical Section ..... signal (mutex); 

뮤텍스 사용

뮤텍스는 키(뮤텍스)를 갖고 작업을 진행할 수 있는 생산자 또는 소비자에 대한 상호 배제를 제공합니다. 생산자가 버퍼를 채우는 한 사용자는 기다려야 하며 그 반대의 경우도 마찬가지입니다. Mutex 잠금에서는 항상 단일 스레드만 전체 버퍼에 대해 작업할 수 있습니다.

프로그램이 시작되면 시스템에 특정 리소스에 대한 뮤텍스 개체를 생성하도록 요청합니다. 시스템은 고유한 이름이나 ID를 사용하여 뮤텍스 개체를 생성합니다. 프로그램 스레드가 리소스를 사용하려고 할 때마다 뮤텍스 개체에 대한 잠금을 차지하고 리소스를 활용하며 사용 후에는 뮤텍스 개체에 대한 잠금을 해제합니다. 그런 다음 다음 프로세스는 뮤텍스 개체에 대한 잠금을 획득할 수 있습니다.

그 동안 프로세스는 뮤텍스 개체에 대한 잠금을 획득했으며 다른 스레드나 프로세스는 해당 리소스에 액세스할 수 없습니다. 뮤텍스 개체가 이미 잠겨 있는 경우 뮤텍스 개체에 대한 잠금을 획득하려는 프로세스는 기다려야 하며 뮤텍스 개체가 잠금 해제될 때까지 시스템에 의해 큐에 대기해야 합니다.

뮤텍스의 장점

뮤텍스의 장점은 다음과 같습니다.

  • 뮤텍스는 중요한 섹션에 진입했다가 해제하기 전에 획득한 단순한 잠금입니다.
  • 주어진 시간에 하나의 스레드만 임계 섹션에 있기 때문에 경쟁 조건이 없으며 데이터는 항상 일관성을 유지합니다.

뮤텍스의 단점

Mutex에는 다음과 같은 몇 가지 단점도 있습니다.

  • 스레드가 잠금을 획득하고 절전 모드로 전환되거나 선점되면 다른 스레드는 앞으로 나아갈 수 없습니다. 이는 기아로 이어질 수 있습니다.
  • 이를 획득한 컨텍스트와 다른 컨텍스트에서는 잠그거나 잠금 해제할 수 없습니다.
  • 임계 섹션에는 한 번에 하나의 스레드만 허용되어야 합니다.
  • 정상적인 구현에서는 바쁜 대기 상태가 되어 CPU 시간이 낭비될 수 있습니다.

세마포어란 무엇입니까?

세마포어는 단순히 음수가 아니고 스레드 간에 공유되는 변수입니다. 세마포어는 신호 메커니즘이며, 다른 스레드는 세마포어를 기다리고 있는 스레드에 신호를 보낼 수 있습니다.

뮤텍스와 세마포어

세마포어는 두 가지 원자 연산을 사용합니다.

1. 잠깐만요: 대기 작업은 인수 S의 값이 양수인 경우 감소합니다. S가 음수이거나 0이면 아무 작업도 수행되지 않습니다.

 wait(S) { while (S<=0); s--; } < pre> <p> <strong>2. Signal for the process synchronization:</strong> The signal operation increments the value of its argument S.</p> <pre> signal(S) { S++; } </pre> <p>A semaphore either allows or reject access to the resource, depending on how it is set up.</p> <h3>Use of Semaphore</h3> <p>In the case of a single buffer, we can separate the 4 KB buffer into four buffers of 1 KB. Semaphore can be associated with these four buffers, allowing users and producers to work on different buffers simultaneously.</p> <h3>Types of Semaphore</h3> <p>Semaphore is distinguished by the operating system in two categories <strong>Counting semaphore</strong> and <strong>Binary semaphore</strong> .</p> <p> <strong>1. Counting Semaphore:</strong> The semaphore S value is initialized to the <strong>number of resources</strong> present in the system. Whenever a process wants to access the resource, it performs <strong>the wait()</strong> operation on the semaphore and <strong>decrements</strong> the semaphore value by one. When it releases the resource, it performs <strong>the signal()</strong> operation on the semaphore and <strong>increments</strong> the semaphore value by one.</p> <p>When the semaphore count goes to 0, it means the processes occupy all resources. A process needs to use a resource when the semaphore count is 0. It executes the <strong>wait()</strong> operation and gets <strong>blocked</strong> until the semaphore value becomes greater than 0.</p> <img src="//techcodeview.com/img/operating-system/67/mutex-vs-semaphore-3.webp" alt="Mutex vs Semaphore"> <p> <strong>2. Binary semaphore:</strong> The value of a semaphore ranges between <strong>0</strong> and <strong>1</strong> . It is similar to mutex lock, but mutex is a locking mechanism, whereas the semaphore is a signaling mechanism. In binary semaphore, if a process wants to access the resource, it performs <strong>the wait()</strong> operation on the semaphore and decrements the value of the semaphore from 1 to 0. When it releases the resource, it performs a <strong>signal</strong> <strong>()</strong> operation on the semaphore and increments its value to 1. Suppose the value of the semaphore is 0 and a process wants to access the resource. In that case, it performs <strong>wait()</strong> operation and block itself till the current process utilizing the resources releases the resource.</p> <img src="//techcodeview.com/img/operating-system/67/mutex-vs-semaphore-4.webp" alt="Mutex vs Semaphore"> <h3>Advantages of Semaphore</h3> <p>Here are the following advantages of semaphore, such as:</p> <ul> <li>It allows more than one thread to access the critical section.</li> <li>Semaphores are machine-independent.</li> <li>Semaphores are implemented in the machine-independent code of the microkernel.</li> <li>They do not allow multiple processes to enter the critical section.</li> <li>As there is busy and waiting in semaphore, there is never wastage of process time and resources.</li> <li>They are machine-independent, which should be run in the machine-independent code of the microkernel.</li> <li>They allow flexible management of resources.</li> </ul> <h3>Disadvantage of Semaphores</h3> <p>Semaphores also have some disadvantages, such as:</p> <ul> <li>One of the biggest limitations of a semaphore is priority inversion.</li> <li>The operating system has to keep track of all calls to wait and signal semaphore.</li> <li>Their use is never enforced, but it is by convention only.</li> <li>The Wait and Signal operations require to be executed in the correct order to avoid deadlocks in semaphore.</li> <li>Semaphore programming is a complex method, so there are chances of not achieving mutual exclusion.</li> <li>It is also not a practical method for large scale use as their use leads to loss of modularity.</li> <li>Semaphore is more prone to programmer error</li> <li>, and it may cause deadlock or violation of mutual exclusion due to programmer error.</li> </ul> <h3>Difference between Mutex and Semaphore</h3> <p>The basic difference between semaphore and mutex is that semaphore is a signalling mechanism, i.e. processes perform wait() and signal() operation to indicate whether they are acquiring or releasing the resource. In contrast, a mutex is a locking mechanism, and the process has to acquire the lock on a mutex object if it wants to acquire the resource. Here are some more differences between semaphore and mutex, such as:</p> <img src="//techcodeview.com/img/operating-system/67/mutex-vs-semaphore-5.webp" alt="Mutex vs Semaphore"> <br> <table class="table"> <tr> <th>Terms</th> <th>Mutex</th> <th>Semaphore</th> </tr> <tr> <td>Definition</td> <td>The mutex is a locking mechanism, as to acquire a resource, a process needs to lock the mutex object, and while releasing a resource process has to unlock the mutex object.</td> <td>Semaphore is a signalling mechanism as wait() and signal() operations performed on the semaphore variable indicate whether a process is acquiring or releasing the resource.</td> </tr> <tr> <td>Existence</td> <td>A mutex is an object.</td> <td>Semaphore is an integer variable.</td> </tr> <tr> <td>Function</td> <td>Mutex allows multiple program threads to access a single resource but not simultaneously.</td> <td>Semaphore allows multiple program threads to access a finite instance of resources.</td> </tr> <tr> <td>Ownership</td> <td>Mutex object lock is released only by the process that has acquired the lock on the mutex object.</td> <td>Semaphore value can be changed by any process acquiring or releasing the resource by performing wait() and signal() operation.</td> </tr> <tr> <td>Categorize</td> <td>Mutex is not categorized further.</td> <td>The semaphore can be categorized into counting semaphore and binary semaphore.</td> </tr> <tr> <td>Operation</td> <td>The mutex object is locked or unlocked by the process of requesting or releasing the resource.</td> <td>Semaphore value is modified using wait() and signal() operation apart from initialization.</td> </tr> <tr> <td>Resources Occupied</td> <td>If a mutex object is already locked, then the process desiring to acquire resource waits and get queued by the system till the resource is released and the mutex object gets unlocked.</td> <td>Suppose the process acquires all the resources, and no resource is free. In that case, the process desiring to acquire resource performs wait() operation on semaphore variable and blocks itself till the count of semaphore become greater than 0.</td> </tr> </table> <hr></=0);>

세마포어는 설정 방법에 따라 리소스에 대한 액세스를 허용하거나 거부합니다.

세마포어 사용

단일 버퍼의 경우 4KB 버퍼를 1KB 버퍼 4개로 분리할 수 있습니다. 세마포어는 이 4개의 버퍼와 연결될 수 있으므로 사용자와 생산자가 서로 다른 버퍼에서 동시에 작업할 수 있습니다.

세마포어의 유형

세마포어는 운영 체제에 따라 두 가지 범주로 구분됩니다. 세마포어 계산 그리고 바이너리 세마포어 .

1. 세마포어 계산: 세마포어 S 값은 다음으로 초기화됩니다. 리소스 수 시스템에 존재합니다. 프로세스가 리소스에 접근하려고 할 때마다 다음을 수행합니다. 기다림() 세마포어에 대한 연산과 감소 세마포어 값을 1로 합니다. 리소스를 해제하면 다음을 수행합니다. 신호() 세마포어에 대한 연산과 증분 세마포어 값을 1로 합니다.

세마포어 수가 0이 되면 프로세스가 모든 리소스를 점유한다는 의미입니다. 프로세스는 세마포어 카운트가 0일 때 리소스를 사용해야 합니다. 기다리다() 작업 및 가져오기 막힌 세마포어 값이 0보다 커질 때까지.

뮤텍스와 세마포어

2. 바이너리 세마포어: 세마포어의 값은 다음 사이에 있습니다. 0 그리고 1 . 뮤텍스 잠금과 유사하지만 뮤텍스는 잠금 메커니즘인 반면 세마포는 신호 메커니즘입니다. 바이너리 세마포어에서는 프로세스가 리소스에 액세스하려는 경우 다음을 수행합니다. 기다림() 세마포어에 대한 연산을 수행하고 세마포어 값을 1에서 0으로 감소시킵니다. 리소스를 해제할 때 다음을 수행합니다. 신호 () 세마포어에 대한 연산을 수행하고 그 값을 1로 증가시킵니다. 세마포어의 값이 0이고 프로세스가 리소스에 액세스하려고 한다고 가정합니다. 이 경우 수행됩니다. 기다리다() 리소스를 활용하는 현재 프로세스가 리소스를 해제할 때까지 작업을 수행하고 자체를 차단합니다.

뮤텍스와 세마포어

세마포어의 장점

세마포어의 장점은 다음과 같습니다.

  • 둘 이상의 스레드가 임계 섹션에 액세스할 수 있습니다.
  • 세마포어는 기계 독립적입니다.
  • 세마포어는 마이크로커널의 기계 독립적인 코드로 구현됩니다.
  • 여러 프로세스가 임계 섹션에 들어가는 것을 허용하지 않습니다.
  • Semaphore에는 Busy와 Waiting이 있기 때문에 처리 시간과 자원의 낭비가 전혀 없습니다.
  • 이는 기계 독립적이며 마이크로커널의 기계 독립적 코드에서 실행되어야 합니다.
  • 이를 통해 리소스를 유연하게 관리할 수 있습니다.

세마포어의 단점

세마포어에는 다음과 같은 몇 가지 단점도 있습니다.

  • 세마포어의 가장 큰 한계 중 하나는 우선순위 반전입니다.
  • 운영 체제는 대기 및 신호 세마포어에 대한 모든 호출을 추적해야 합니다.
  • 해당 사용은 강제되지 않으며 관례에 따른 것입니다.
  • 세마포어의 교착 상태를 방지하려면 대기 및 신호 작업을 올바른 순서로 실행해야 합니다.
  • 세마포어 프로그래밍은 복잡한 방법이므로 상호 배제를 달성하지 못할 가능성이 있습니다.
  • 또한 모듈성을 상실하게 되므로 대규모 사용에는 실용적인 방법이 아닙니다.
  • 세마포어는 프로그래머 오류가 발생하기 쉽습니다.
  • , 프로그래머 오류로 인해 교착상태나 상호 배제 위반이 발생할 수 있습니다.

뮤텍스와 세마포어의 차이점

세마포어와 뮤텍스의 기본적인 차이점은 세마포어가 신호 메커니즘이라는 것입니다. 즉, 프로세스는 자원을 획득하거나 해제하는지 여부를 나타내기 위해 wait() 및 signal() 작업을 수행합니다. 대조적으로, 뮤텍스는 잠금 메커니즘이며 프로세스가 리소스를 획득하려면 뮤텍스 개체에 대한 잠금을 획득해야 합니다. 세마포어와 뮤텍스의 차이점은 다음과 같습니다.

뮤텍스와 세마포어
자귀 뮤텍스 신호기
정의 뮤텍스는 잠금 메커니즘으로, 리소스를 획득하려면 프로세스가 뮤텍스 개체를 잠그고 리소스 프로세스를 해제하는 동안 뮤텍스 개체를 잠금 해제해야 합니다. 세마포어는 세마포어 변수에 대해 수행되는 wait() 및 signal() 작업이 프로세스가 리소스를 획득하는지 또는 해제하는지 여부를 나타내는 신호 메커니즘입니다.
존재 뮤텍스는 객체입니다. 세마포어는 정수 변수입니다.
기능 Mutex를 사용하면 여러 프로그램 스레드가 단일 리소스에 액세스할 수 있지만 동시에 액세스할 수는 없습니다. 세마포어를 사용하면 여러 프로그램 스레드가 유한한 리소스 인스턴스에 액세스할 수 있습니다.
소유권 뮤텍스 개체 잠금은 뮤텍스 개체에 대한 잠금을 획득한 프로세스에 의해서만 해제됩니다. 세마포어 값은 wait() 및 signal() 작업을 수행하여 리소스를 획득하거나 해제하는 모든 프로세스에 의해 변경될 수 있습니다.
분류 뮤텍스는 더 이상 분류되지 않습니다. 세마포어는 카운팅 세마포어와 바이너리 세마포어로 분류할 수 있습니다.
작업 뮤텍스 개체는 리소스를 요청하거나 해제하는 과정에서 잠기거나 잠금 해제됩니다. 초기화 외에 wait(), signal() 연산을 이용하여 세마포어 값을 수정한다.
점유된 자원 뮤텍스 개체가 이미 잠겨 있으면 리소스를 획득하려는 프로세스는 리소스가 해제되고 뮤텍스 개체가 잠금 해제될 때까지 시스템에서 대기하고 큐에 들어갑니다. 프로세스가 모든 리소스를 획득하고 무료 리소스가 없다고 가정합니다. 이 경우 자원을 획득하려는 프로세스는 세마포 변수에 대해 wait() 연산을 수행하고 세마포 개수가 0보다 커질 때까지 자신을 차단합니다.