打通用戶態程序和內核系列之二:pthread_mutex_lock的實現

一個很容混淆的地方是,誤以爲用戶程序鎖API的實現和接口,最終也會調用內核相關的鎖操作提供的API。

應用程序鎖API接口

主要的API有:
pthread_mutex_lock;

相關說明如下:

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;

相關說明如下:

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 數據結構在中定義,主要的成員如下:


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章