Linux mutex lock, linux mutex
In multi-thread control, multiple threads can access Shared resources through mutex locks. At the same time, only one thread can master the mutex lock. Only this thread can access shared resources, and other threads are blocked until the mutex lock is released. If multiple threads are blocked during the lock, all blocked threads are set to the executable state. The first execution thread obtains control of the mutex lock and locks the lock. Other threads continue to block.1. Create a mutex lockMutex locks can be created either statically or dynamically.Static creation:Pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;Note: In ubuntu14.04, only the default lock is available among the three locks because the ifdef Conditional compilation is used in the header file. For details, refer to the header file.Pthread. h # define PTHREAD_MUTEX_INITIALIZER \
{0, 0, 0, 0, 0, {_ PTHREAD_SPINS }}}
#Ifdef _ USE_GNU // If use is not definedGnu does not have the following locks:
# Define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
{0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, 0, {_ PTHREAD_SPINS }}}
# Define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP \
{0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, 0, {_ PTHREAD_SPINS }}}
# Define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP \
{0, 0, 0, PTHREAD_MUTEX_ADAPTIVE_NP, 0, {_ PTHREAD_SPINS }}}
Dynamic Creation:The pthread_mutex_init function is dynamically created. The prototype of the function is: int pthread_mutex_init (pthread_mutex_t * mutex, const worker * attr) such as pthread_mutex_init (mutex, NULL). The default attribute is used, this is a quick mutex lock.
Binary lock attributesThe mutex attribute can be initialized by the function pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * attr. The mutex lock type can be set to the following values:
PTHREAD_MUTEX_TIMED_NP, which is the default value, that is, the common lock, also called the quick mutex lock. PTHREAD_MUTEX_RECURSIVE_NP: recursive mutex lock and nested lock. The same thread can successfully obtain the same lock multiple times and unlock it through multiple unlocks. PTHREAD_MUTEX_ERRORCHECK_NP: check error mutex lock. Check error lock. If the same thread requests the same lock, EDEADLK is returned. Otherwise, it is the same as PTHREAD_MUTEX_TIMED_NP. In the pthread_mutex_init () function, the second parameter attr is the struct, and the preceding three parameters are int. Therefore, you cannot directly import the preceding three values. You can use the following two functions to set and obtain the attr value. Pthread_mutexattr_settype (pthread_mutexattr_t * attr, int type): Set the lock attribute type to attr. Then (pthread_mutexattr_t * attr, int * type) gets the lock attribute from attr, store in pointer type.
The use of mutex is relatively simple and will not be detailed in detail.