一个很容混淆的地方是,误以为用户程序锁API的实现和接口,最终也会调用内核相关的锁操作提供的API。

应用程序锁API接口

主要的API有:
pthread_mutex_lock;

相关说明如下:

NAME
     pthread_mutex_lock -- lock a mutex

SYNOPSIS
     #include 

     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;

相关说明如下:

PTHREAD_MUTEX_UNLOCK(3)  BSD Library Functions Manual  PTHREAD_MUTEX_UNLOCK(3)

NAME
     pthread_mutex_unlock -- unlock a mutex

SYNOPSIS
     #include 

     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 数据结构在中定义,主要的成员如下:


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/73498640