Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pthread_mutex_lock is implemented

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.

like image 740
avd Avatar asked Feb 23 '11 19:02

avd


People also ask

Does pthread_mutex_lock use any system calls?

There are three system calls which perform operations on a mutex, each of which takes a pointer to a pthread_mutex_t as an argument. int pthread_mutex_lock(pthread_mutex_t *mutex);

How is mutex implemented?

A mutex is initialized in the beginning of the main function. The same mutex is locked in the 'trythis()' function while using the shared resource 'counter'. At the end of the function 'trythis()' the same mutex is unlocked. At the end of the main function when both the threads are done, the mutex is destroyed.

What is the use of pthread_mutex_lock?

The pthread_mutex_lock() function acquires ownership of the mutex specified. If the mutex currently is locked by another thread, the call to pthread_mutex_lock() blocks until that thread relinquishes ownership by a call to pthread_mutex_unlock().


2 Answers

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

like image 52
gby Avatar answered Sep 18 '22 14:09

gby


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

Check this reference.

like image 30
karlphillip Avatar answered Sep 18 '22 14:09

karlphillip