The mutex is essentially a lock that provides protected access to the shared resource.
1. Initialize:
Under Linux, the mutex data type for a thread is pthread_mutex_t. Initialize it before use:
For a statically allocated mutex, you can set it to Pthread_mutex_initializer, or call Pthread_mutex_init.
For a dynamically allocated mutex, after the request for memory (malloc), the Pthread_mutex_init is initialized and the Pthread_mutex_destroy needs to be called before releasing the memory (free).
Prototype:
int Pthread_mutex_init (pthread_mutex_t *restrict Mutex, const pthread_mutexattr_t *restric attr);
int Pthread_mutex_destroy (pthread_mutex_t *mutex);
Header file:
Return value: Success returns 0, error number is returned.
Description: If you initialize the mutex with the default property, simply set the attr to null. Other values are explained later.
2. Mutex Operation:
Access to the shared resource is to lock the mutex, and if the mutex is already locked, the calling thread blocks until the mutex is unlocked. After the access to the shared resource has been completed, the mutex is unlocked.
First, the lock function:
Header file:
Prototype:
int Pthread_mutex_lock (pthread_mutex_t *mutex);
int Pthread_mutex_trylock (pthread_mutex_t *mutex);
Return value: Success returns 0, error number is returned.
Description: Specifically say the Trylock function, this function is non-blocking invocation mode, that is, if the mutex is not locked, the Trylock function will lock the mutex and gain access to the shared resources; If the mutex is locked, the Trylock function will not block the wait and return ebusy directly, indicating that the shared resource is busy.
Again, the function of the solution:
Header file:
Prototype: int Pthread_mutex_unlock (pthread_mutex_t *mutex);
Return value: Success returns 0, error number is returned.
3. Deadlock:
A deadlock occurs when multiple dependent locks exist, and occurs when one thread attempts to lock the mutex in reverse order with another thread. How to avoid deadlocks is something that you should pay extra attention to using mutexes.
Generally speaking, there are several unwritten basic principles:
Be sure to obtain a lock before you operate on a shared resource.
Be sure to release the lock after you complete the operation.
Occupy the lock as quickly as possible.
If there are multiple locks, such as the Order of acquisition is the ABC chain buckle, the release order should also be ABC.
When a thread error returns, it should release the lock it acquired.
Mutex in a POSIX thread