4

I was going through concurrency section from REMZI and while going through mutex section, and I got confused about this:

To avoid busy waiting, mutex implementations employ park() / unpark() mechanism (on Sun OS) which puts a waiting thread in a queue with its thread ID. Later on during pthread_mutex_unlock() it removes one thread from the queue so that it can be picked by the scheduler. Similarly, an implementation of Futex (mutex implementation on Linux) uses the same mechanism.

  1. It is still unclear to me where the queue lies. Is it in the address space of the running process or somewhere inside the kernel?

  2. Another doubt I had is regarding condition variables. Do pthread_cond_wait() and pthread_cond_signal() use normal signals and wait methods, or do they use some variant of it?

Jamal
  • 763
  • 7
  • 22
  • 32
pankaj
  • 1,316
  • 3
  • 16
  • 27

1 Answers1

6

Doubt 1: But, it is still unclear to me where actually does the queue lies. Is it in the address space of the running process or somewhere inside kernel.

Every mutex has an associated data structure maintained in the kernel address space, in Linux it is futex. That data structure has an associated wait queue where threads from different processes can queue up and wait to be woken up, see futex_wait kernel function.

Doubt 2: Another doubt I had is regarding condition variables, does pthread_cond_wait() and pthread_cond_signal() use normal signal and wait methods OR they use some variant of it.

Modern Linux does not use signals for condition variable signaling. See NPTL: The New Implementation of Threads for Linux for more details:

The addition of the Fast Userspace Locking (futex) into the kernel enabled a complete reimplementation of mutexes and other synchronization mechanisms without resorting to interthread signaling. The futex, in turn, was made possible by the introduction of preemptive scheduling to the kernel.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271