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时会发生什么?有什么指针在使用吗?对源代码的引用真的很有帮助。
2 个解决方案
#1
47
It is both complicated and differs from Unix to Unix variant.
它既复杂又不同于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/futex and http://en.wikipedia.org/wiki/Futex
更多细节请参见:http://linux.die.net/man/2/futex和http://en.wikipedia.org/wiki/Futex
#2
#1
47
It is both complicated and differs from Unix to Unix variant.
它既复杂又不同于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/futex and http://en.wikipedia.org/wiki/Futex
更多细节请参见:http://linux.die.net/man/2/futex和http://en.wikipedia.org/wiki/Futex