如何实现pthread_mutex_lock [英] How pthread_mutex_lock is implemented

查看:814
本文介绍了如何实现pthread_mutex_lock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道如何在Unix内部实现与线程之间的同步相关的功能.例如,当我呼叫pthread_mutex_lock时会发生什么?有没有使用中的指针?引用源代码确实有帮助.

I am just curious to know how functions related to synchronization between threads are implemented inside Unix. For example, what happens when I call pthread_mutex_lock? Are there any pointers in use? A reference to the source code would really help.

推荐答案

它既复杂又因Unix与Unix的不同而不同.

It is both complicated and differs from Unix to Unix variant.

例如,在Linux中,使用了称为Futex(快速用户空间互斥锁的简称)的系统.

In Linux, for example, a system called Futex (Short for Fast Userspace Mutex) is used.

在此系统中,对用户空间中的互斥变量执行原子增量和测试操作.

In this system an atomic increment and test operation is performed on the mutex variable in user space.

如果操作结果表明锁上没有争用,则对pthread_mutex_lock的调用将返回,而无需将上下文切换到内核中,因此获取互斥量的操作可以非常快.

If the result of the operation indicates that there was no contention on the lock, the call to pthread_mutex_lock returns without ever context switching into the kernel, so the operation of taking a mutex can be very fast.

仅当检测到争用时,系统调用(称为futex)才会发生,并且上下文切换到内核中,这会使调用进程进入睡眠状态,直到释放互斥锁为止.

Only if contention was detected does a system call (called futex) and context switch into the kernel occurs that puts the calling process to sleep until the mutex is released.

还有很多更多的细节,尤其是对于可靠和/或优先级继承互斥,但这就是它的本质.

There are many many more details, especially for reliable and/or priority inhertience mutexes, but this is the essence of it.

有关更多详细信息,请参见: http://linux.die.net/man/2/futex http://en.wikipedia.org/wiki/Futex

For more details see: http://linux.die.net/man/2/futex and http://en.wikipedia.org/wiki/Futex

这篇关于如何实现pthread_mutex_lock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆