Home  >  Article  >  What is the difference between semaphore and mutex

What is the difference between semaphore and mutex

青灯夜游
青灯夜游Original
2021-11-08 14:24:3918480browse

Difference: 1. Mutex is used for mutual exclusion of threads, and semaphore is used for thread synchronization; 2. Mutex value can only be 0 or 1, and semaphore value can be a non-negative integer; 3. The locking and unlocking of the mutex must be used by the same thread respectively. The semaphore can be released by one thread and obtained by another thread.

What is the difference between semaphore and mutex

The operating environment of this tutorial: Windows 7 system, Dell G3 computer.

The difference between mutex and semaphore

1. Mutex is used for mutual exclusion of threads, and semaphore is used for synchronization of threads.

This is the fundamental difference between mutexes and semaphores, that is, the difference between mutual exclusion and synchronization.

Mutual exclusion: refers to a resource that only allows one visitor to access it at the same time, and is unique and exclusive. But mutual exclusion cannot limit the order in which visitors access resources, that is, access is unordered.

Synchronization: refers to the orderly access of resources by visitors through other mechanisms on the basis of mutual exclusion (in most cases). In most cases, synchronization already implements mutual exclusion, especially when all writes to resources must be mutually exclusive. A few cases allow multiple visitors to access resources at the same time

2. The mutex value can only be 0/1, and the semaphore value can be a non-negative integer.

In other words, a mutex can only be used for mutually exclusive access to one resource, and it cannot implement multi-thread mutual exclusion of multiple resources. Semaphore can realize multi-thread mutual exclusion and synchronization of multiple similar resources. When the semaphore is a single-valued semaphore, mutually exclusive access to a resource can also be completed.

3. The locking and unlocking of the mutex must be used by the same thread respectively. The semaphore can be released by one thread and obtained by another thread.

Mutex (Mutex)

The mutex is a data structure that represents the mutual exclusion phenomenon and is also used as a binary semaphore. A mutex is basically a multitasking-sensitive binary signal that can be used to synchronize the behavior of multiple tasks. It is often used to protect critical sections of code from interrupts and to share resources used in synchronization.

What is the difference between semaphore and mutex

Mutex is essentially a lock, providing exclusive access to resources, so the main function of Mutex is for mutual exclusion. The value of the Mutex object has only two values ​​​​0 and 1. These two values ​​​​also represent the two states of Mutex respectively. The value is 0, indicating the locking state. The current object is locked. If the user process/thread attempts to Lock critical resources, it will enter the queue and wait; the value is 1, indicating the idle state. The current object is idle, and the user process/thread can Lock critical resources. Afterwards, the Mutex value decreases by 1 and becomes 0.

Mutex can be abstracted into four operations:

-Create

-Lock

-Unlock

- DestroyDestroy

Mutex can have an initial value when it is created, indicating whether the Mutex is in a locked state or an idle state after it is created. In the same thread, in order to prevent deadlock, the system does not allow the Mutex to be locked twice in a row (the system usually returns immediately after the second call). In other words, the two corresponding operations of locking and unlocking need to be completed in the same thread.

Mutex functions provided in different operating systems:

Deadlock mainly occurs when there are multiple dependent locks, and it occurs when one thread tries to lock the mutex in the opposite order as another thread. How to avoid deadlock is something that should be paid special attention to when using mutexes. .

Generally speaking, there are several unwritten basic principles:

You must obtain a lock before operating on shared resources.

Be sure to release the lock after completing the operation.

Seize the lock for as short a time as possible.

If there are multiple locks, if the acquisition order is ABC chain lock, the release order should also be ABC.

When a thread returns with an error, it should release the lock it acquired.

Perhaps some readers are curious, how to implement the operations of "suspend waiting" and "wake up waiting thread"? Each Mutex has a waiting queue. If a thread wants to wait on the Mutex, it must first add itself to the waiting queue, then set the thread status to sleep, and then call the scheduler function to switch to another thread. If a thread wants to wake up other threads in the waiting queue, it only needs to take out an item from the waiting queue, change its status from sleep to ready, and join the ready queue. Then it may switch to being awakened the next time the scheduler function is executed. the rout.

Under normal circumstances, if the same thread calls lock twice, during the second call, because the lock is already occupied, the thread will hang up and wait for other threads to release the lock. However, the lock is occupied by If the lock is occupied by itself, the thread is suspended without a chance to release the lock, so it is always in a suspended waiting state. This is called deadlock. Another typical deadlock situation is this: Thread A acquires lock 1, and thread B acquires lock 2. At this time, thread A calls lock to try to acquire lock 2. As a result, it needs to hang and wait for thread B to release lock 2, and this At this time, thread B also calls lock to try to obtain lock 1. As a result, it needs to wait for thread A to release lock 1, so both threads A and B are in a suspended state forever. It is not difficult to imagine that if more threads and more locks are involved, the problem of possible deadlock will become complicated and difficult to judge.

Semaphore

Semaphore, sometimes called a semaphore, is a facility used in a multi-threaded environment. It is responsible for coordinating various threads. To ensure that they can use public resources correctly and reasonably.

Semaphore can be divided into several categories:

  • Binary semaphore (binary semaphore): Only the semaphore is allowed to take the value 0 or 1, and it can only be used by one at the same time Thread acquisition.

  • Integer semaphore (integer semaphore): The semaphore value is an integer, which can be obtained by multiple threads at the same time until the semaphore value becomes 0.

  • Record semaphore (record semaphore): In addition to an integer value value (count), each semaphore s also has a waiting queue List, which is blocked on the semaphore. The identification of each thread. When a semaphore is released and the value is incremented by one, the system automatically wakes up a waiting thread from the waiting queue, allowing it to obtain the semaphore, and at the same time the semaphore is decremented by one.

The semaphore controls access to shared resources through a counter. The value of the semaphore is a non-negative integer, and all threads passing it will reduce the integer by one. If the counter is greater than 0, access is allowed and the counter is decremented by 1; if it is 0, access is prohibited and all threads trying to pass it will be in a waiting state.

The result of the counter calculation is the pass allowed to access the shared resource. Therefore, in order to access a shared resource, a thread must get a pass from the semaphore. If the semaphore's count is greater than 0, then this thread gets a pass, which will cause the semaphore's count to be decremented. Otherwise, this thread will block until it gets a pass. until. When this thread no longer needs to access the shared resource, it releases the pass, which causes the semaphore's count to be incremented, and if another thread is waiting for the pass, that thread will get the pass at that time.

Semaphore can be abstracted into five operations:

  • - Create Create

  • - Wait for Wait:

    The thread waits for the semaphore. If the value is greater than 0, it is obtained and the value is reduced by one; if it is only equal to 0, the thread enters the sleep state until the semaphore value is greater than 0 or times out.

  • -Release Post

    executes the release of the semaphore, and the value is increased by one; if there is a waiting thread at this time, the thread is awakened.

  • -Trying to wait for TryWait

    If TryWait is called, the thread does not actually obtain the semaphore, but checks whether the semaphore can be obtained. If the semaphore value is greater than 0, TryWait returns success; otherwise it returns failure.

  • -Destroy

Semaphores can be used to protect two or more key code segments. These key code segments cannot be called concurrently. Before entering a critical section of code, the thread must obtain a semaphore. If there are no threads in the critical section of code, the thread immediately enters that part of the block diagram. Once the critical section of code is complete, the thread must release the semaphore. Other threads that want to enter this critical code section must wait until the first thread releases the semaphore. In order to complete this process, you need to create a semaphore, and then place the Acquire Semaphore VI and Release Semaphore VI at the beginning and end of each key code segment. Make sure that these semaphore VIs refer to the originally created semaphore.

Action/System

Win32

Linyx

Solaris

Create

CreateMutex

##pthread_mutex_init

mutex_init

Lock

WaitForSingleObject

pthread_mutex_lock

mutex_lock

Unlock

ReleaseMutex

pthread_mutex_unlock

mutex_unlock

Destroy

CloseHandle

pthread_mutex_destroy

mutex_destroy

##For more related knowledge, please Visit the

Action/System

Win32

POSIX

Create

CreateSemaphore

##sem_init

Wait

WaitForSingleObject

sem _wait

Release

ReleaseMutex

sem _post

Try to wait

WaitForSingleObject

sem _trywait

Destroy

CloseHandle

sem_destroy

FAQ

section!

The above is the detailed content of What is the difference between semaphore and mutex. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn