Issue
We can use mutex lock in POSIX API as follows:
/* acquire the mutex lock */
pthread_mutex_lock(&mutex);
/* critical section */
/* release the mutex lock */
pthread_mutex_unlock(&mutex);
Does POSIX API put waiting thread to sleep? Where is the waiting queue? Is the waiting queue not visible to user?
Solution
Does POSIX API put waiting thread to sleep?
The POSIX API is just an API, it can be implemented in different ways.
In Linux, the POSIX Threads library uses futexes to implement mutexes. When a mutex is contended, the pthread implementation will use the futex(2)
syscall to request intervention from the kernel, which puts to sleep or wakes up threads as needed. So yes, threads can definitely be put to sleep when calling pthread_mutex_lock()
.
One thing to note, as the Wikipedia article suggests, is that: a properly programmed futex-based lock does not use system calls except when the lock is contended. And this is exactly the case for the POSIX Thread library, so you may have perfectly functioning and syncronized programs using threads that never issue futex(2)
syscalls.
Where is the waiting queue? Is the waiting queue not visible to user?
Since mutexes are bases on futexes, and futex contention is ultimately handled by the kernel, the waiting queue resides in kernel space, and is not visible from user space. You can see the implementation right in the file kernel/futex.c
from the Linux kernel source code.
Answered By - Marco Bonelli Answer Checked By - Robin (WPSolving Admin)