我是靠谱客的博主 帅气眼神,这篇文章主要介绍打通用户态程序和内核系列之二:pthread_mutex_lock的实现应用程序锁API接口用户态锁的实现参考链接,现在分享给大家,希望可以做个参考。

一个很容混淆的地方是,误以为用户程序锁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

最后

以上就是帅气眼神最近收集整理的关于打通用户态程序和内核系列之二:pthread_mutex_lock的实现应用程序锁API接口用户态锁的实现参考链接的全部内容,更多相关打通用户态程序和内核系列之二:pthread_mutex_lock内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部