One of the interview questions for C/C ++, a Linux Application Development Engineer: synchronization of multi-threaded programs in Linux
Reference: three methods for Linux Thread Synchronization
In Linux, the most common three methods of thread synchronization are mutex lock, condition variable, and semaphore.
Mutex locks are used to synchronize threads. The lock mechanism allows only one thread to execute a key part of the code at the same time.
Conditional variables are used to wait, not to lock a thread. A condition variable is used to automatically block a thread until a special situation occurs. Usually the condition variables and mutex locks are used at the same time.
The semaphores used in inter-process communication are the same concept. They are special variables that can be increased or decreased, however, the key access to the program is ensured to be atomic operations. If multiple threads in a program attempt to change the value of a semaphore, the system will ensure that all operations will be performed in turn.
The most commonly used semaphores are binary semaphores, which can have only 0 and 1 values, sometimes also called Single-value semaphores.
But there is a problem: how do I select a semaphore or mutex lock during thread synchronization?
Here Baidu has a difference on mutex lock and semaphore:
1. mutex lock is used for thread mutex and semaphores are used for thread synchronization;
This is the fundamental difference between the two, that is, the difference between mutex and synchronization.
Mutual Exclusion: A Resource allows only one visitor to access it at the same time, which is unique and exclusive. However, mutual exclusion cannot limit the access sequence of visitors to the resource, that is, access is out of order.
Synchronization: it refers to the mutual exclusion. In most cases, visitors can access resources in an orderly manner through other mechanisms.
In most cases, synchronization has implemented mutex, especially when all resources are written into the database. In a few cases, multiple visitors can access the resources at the same time.
2. The mutex value can only be 0/1, and the signal value can be a non-negative integer.
That is to say, a mutex can only be used for mutex access to one resource. It cannot implement multi-thread mutex problem for multiple resources.
Semaphores can achieve multi-thread mutex and synchronization of multiple similar resources.
When semaphores are single-value semaphores, mutual access to a resource can also be completed.
3. The lock and unlock of mutex must be used by the same thread. The semaphores can be released by one thread and the other.