Linux pthread_mutex_lock 是如何实现的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5095781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How pthread_mutex_lock is implemented
提问by avd
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 中如何实现与线程之间的同步相关的功能。例如,当我打电话时会发生什么pthread_mutex_lock
?是否有任何使用中的指针?对源代码的引用真的很有帮助。
回答by gby
It is both complicated and differs from Unix to Unix variant.
它既复杂又不同于 Unix 到 Unix 变体。
In Linux, for example, a system called Futex (Short for Fast Userspace Mutex) is used.
例如,在 Linux 中,使用了一个名为 Futex(快速用户空间互斥的缩写)的系统。
In this system an atomic increment and test operation is performed on the mutex variable in user space.
在该系统中,对用户空间中的互斥变量执行原子增量和测试操作。
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.
如果操作的结果表明锁上没有争用,则对 pthread_mutex_lock 的调用将返回,而无需将上下文切换到内核中,因此获取互斥锁的操作可以非常快。
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.
只有当检测到争用时,才会进行系统调用(称为 futex)并且上下文切换到内核中,从而使调用进程进入睡眠状态,直到互斥锁被释放。
There are many many more details, especially for reliable and/or priority inhertience mutexes, but this is the essence of it.
还有更多细节,特别是对于可靠和/或优先级继承互斥锁,但这就是它的本质。
For more details see: http://linux.die.net/man/2/futexand http://en.wikipedia.org/wiki/Futex
有关更多详细信息,请参阅:http: //linux.die.net/man/2/futex和http://en.wikipedia.org/wiki/Futex