一個很容混淆的地方是,誤覺得用戶程序鎖API的實現和接口,最終也會調用內核相關的鎖操做提供的API。數據結構
主要的API有:
pthread_mutex_lock;ide
相關說明以下:this
NAME pthread_mutex_lock -- lock a mutex SYNOPSIS #include <pthread.h> int pthread_mutex_lock(pthread_mutex_t *mutex); DESCRIPTION The pthread_mutex_lock() function locks mutex. If the mutex is already locked, the calling thread will block until the mutex becomes available. RETURN VALUES If successful, pthread_mutex_lock() will return zero, otherwise an error number will be returned to indicate the error. ERRORS The pthread_mutex_lock() function will fail if: [EINVAL] The value specified by mutex is invalid. [EDEADLK] A deadlock would occur if the thread blocked waiting for mutex.
pthread_mutex_unlock;.net
相關說明以下:code
PTHREAD_MUTEX_UNLOCK(3) BSD Library Functions Manual PTHREAD_MUTEX_UNLOCK(3) NAME pthread_mutex_unlock -- unlock a mutex SYNOPSIS #include <pthread.h> int pthread_mutex_unlock(pthread_mutex_t *mutex); DESCRIPTION If the current thread holds the lock on mutex, then the pthread_mutex_unlock() function unlocks mutex. Calling pthread_mutex_unlock() with a mutex that the calling thread does not hold will result in undefined behavior. RETURN VALUES If successful, pthread_mutex_unlock() will return zero, otherwise an error number will be returned to indicate the error. ERRORS The pthread_mutex_unlock() function will fail if: [EINVAL] The value specified by mutex is invalid. [EPERM] The current thread does not hold a lock on mutex. SEE ALSO pthread_mutex_destroy(3), pthread_mutex_init(3), pthread_mutex_lock(3), pthread_mutex_trylock(3) STANDARDS The pthread_mutex_unlock() function conforms to ISO/IEC 9945-1:1996 (``POSIX.1'').
用戶鎖相關的操做都涉及到同一個數據結構mutex,mutex 數據結構在中定義,主要的成員以下:orm
typedef union { struct __pthread_mutex_s { int __lock; unsigned int __count; int __owner; #ifdef __x86_64__ unsigned int __nusers; #endif /* KIND must stay at this position in the structure to maintain binary compatibility with static initializers. */ int __kind; #ifdef __x86_64__ short __spins; short __elision; __pthread_list_t __list; # define __PTHREAD_MUTEX_HAVE_PREV 1 /* Mutex __spins initializer used by PTHREAD_MUTEX_INITIALIZER. */ # define __PTHREAD_SPINS 0, 0 #else #endif } __data; char __size[__SIZEOF_PTHREAD_MUTEX_T]; long int __align; } pthread_mutex_t ————————————————
介紹用戶態中pthead_mutex_lock() 的具體實現
https://blog.csdn.net/hzhzh007/article/details/6535437 : 果如所料,最底層也是基於用戶態的lock cmxhg 指令來實現的;
https://blog.csdn.net/luoyuyou/article/details/73498640blog