1) Initialization of the thread lock
Static initialization:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
or dynamic initialization:
int pthread_mutex_init(pthread_mutex_t*mutex,constpthread_mutexattr_t* attr);
Where attr is used to specify the mutex attribute, and if NULL, the default property is used. After the function executes successfully, the mutex is initialized to an unlocked state.
2) operation of the lock
2.1) Locking:
int pthread_mutex_lock(pthread_mutex_t*mutex);int pthread_mutex_trylock(pthread_mutex_t*mutex);
The Pthread_mutex_trylock () method does not block when the lock is occupied, but returns EBUSY
2.2) Release the Lock:
int pthread_mutex_unlock(pthread_mutex_t*mutex);
2.3) Destroy the Lock:
int pthread_mutex_destroy(pthread_mutex_t*mutex);
Destroying a mutex means freeing up the resources it occupies and requires that the lock is currently open. Because the mutex does not occupy any resources in Linux, Pthread_mutex_destroy () in Linuxthreads has no other action in addition to checking the lock state (the lock State returns EBUSY).
3) Properties of the lock
The properties of the mutex are specified when the lock is created, there is only one lock type attribute in the Linuxthreads implementation, and the different lock types behave differently when attempting to lock an already locked mutex.
The current (glibc2.2.3,linuxthreads0.9) has four values to choose from:
This is the default value, which is the normal lock. When a line is Cheng, the remaining thread that requests the lock forms a wait queue, and the lock is acquired by priority after unlocking. This locking strategy guarantees the fairness of resource allocation.
- Pthread_mutex_recursive_np
Nested locks allow the same thread to be successfully acquired multiple times for the same lock and unlocked by multiple unlock. If it is a different thread request, re-competes when the lock line threads unlocked.
- Pthread_mutex_errorcheck_np
The wrong lock is returned if the same thread requests the same lock, otherwise the EDEADLK is the same as the PTHREAD_MUTEX_TIMED_NP type action. This ensures that the simplest case of deadlocks does not occur when multiple locks are not allowed.
- Pthread_mutex_adaptive_np
Adaptive lock, the simplest type of lock, only waiting to be unlocked after re-competition.
Linux Thread Lock pthread_mutex_t