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

查看:47
本文介绍了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 变体而异.

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

例如,在 Linux 中,使用了一个名为 Futex(Short for Fast Userspace Mutex)的系统.

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/futexhttp://en.wikipedia.org/wiki/Futex

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

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