How pthread_mutex_lock is implemented
Asked Answered
D

3

52

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.

Dreeda answered 23/2, 2011 at 19:6 Comment(1)
#3224752Kistler
V
70

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

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.

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.

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.

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

Visit answered 23/2, 2011 at 19:11 Comment(1)
What was used for kernel-assisted wait and wake operations prior to futex?Typesetting
K
6

On Linux, pthreads is available through libc. The usual is glibc, and the source is available here!

Check this reference.

Kistler answered 23/2, 2011 at 19:15 Comment(0)
P
2

I would suggest reading:

https://pages.cs.wisc.edu/~remzi/OSTEP/threads-locks.pdf

from https://pages.cs.wisc.edu/~remzi/OSTEP/ .

I don't think it could be well explained and understood without reading some good texts.

Padding answered 11/9, 2021 at 2:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.