互斥锁是否让等待线程在 POSIX API 中休眠?

Does mutex lock put waiting thread to sleep in POSIX API?

我们可以在POSIXAPI中使用互斥锁,如下:

/* acquire the mutex lock */
pthread_mutex_lock(&mutex);
/* critical section */
/* release the mutex lock */
pthread_mutex_unlock(&mutex);

POSIX API 是否让等待线程休眠?等待队列在哪里?等待队列对用户不可见吗?

Does POSIX API put waiting thread to sleep?

POSIXAPI只是一个API,可以有不同的实现方式

在 Linux 中,POSIX 线程库使用 futexes to implement mutexes. When a mutex is contended, the pthread implementation will use the futex(2) 系统调用来请求内核的干预,根据需要将线程置于睡眠状态或唤醒线程。所以,线程在调用pthread_mutex_lock().

时肯定可以进入休眠状态

正如维基百科文章所建议的,需要注意的一件事是:正确编程的基于 futex 的锁不使用系统调用,除非锁被争用。 POSIX 线程库正是这种情况,因此您可以使用从不发出 futex(2) 系统调用的线程来完美运行和同步程序。

Where is the waiting queue? Is the waiting queue not visible to user?

由于mutexes是基于futexes的,而futex的争用最终是由内核来处理的,等待队列驻留在内核space中,并且是用户 space 不可见。您可以在 Linux 内核源代码的文件 kernel/futex.c 中看到实现。