The difference between semaphores and mutex locks under Linux is: 1. Semaphores are used for synchronization of multi-threads and multi-tasks, while mutex locks are used for mutual exclusion of multi-threads and multi-tasks; 2. Semaphores When one thread completes an action, other threads can then perform certain actions. Once the mutex thread occupies a resource, other threads cannot access it.
#The operating environment of this tutorial: linux7.3 system, Dell G3 computer.
The semaphore (semaphore[ˈseməfɔ:(r)]) is used for multi-thread and multi-task synchronization. A thread completes a certain task. An action is notified to other threads through semaphores, and other threads then perform certain actions.
The mutex lock (Mutual exclusion, abbreviated as Mutex) is used for multi-thread and multi-task mutual exclusion. If one thread occupies a certain resource, other threads cannot access it until this thread is unlocked. Threads can only begin to use this resource.
For example, access to global variables sometimes requires locking. After the operation is completed, it is unlocked. Although the two concepts are somewhat similar, their focus is different. The semaphore is not necessarily about locking a certain resource, but a process concept.
For example: there are two threads A and B, and thread B You have to wait for thread A to complete a certain task before proceeding with the following steps. This task does not necessarily involve locking a certain resource, but can also perform some calculations or data processing.
The thread mutex is the concept of "locking a certain resource". During the lock period, other threads cannot operate on the protected data.
It is not difficult to see that mutex is a special case of semaphore (when n=1).
In other words, the latter can be used to replace the former. However, because mutex is relatively simple and efficient, this design is still used when resource exclusivity must be guaranteed.
Related recommendations: "Linux Video Tutorial"
The above is the detailed content of What is the difference between semaphore and mutex lock under linux. For more information, please follow other related articles on the PHP Chinese website!