POSIX 命名信号量可以同步线程吗?

Can POSIX named semaphores synchronize threads?

我正在寻找一种在 Linux 上同步多个多线程进程的方法。 C++11 风格的互斥锁只在单个进程内的线程之间运行, ans 据我所知,flock 不会相互排斥同一进程的线程。

因此,我想到了POSIX信号量。 我知道未命名的信号量要么与线程相关,要么与进程相关,但不能同时与两者相关。 命名信号量呢?显然他们同步进程,但是线程呢?我在文档中找不到明确的最终答案。

是的,他们同步线程。

The Open Group Base Specification Issue 7 在 General Concepts 下阐明了所有 semaphores synchronize threads,无论它们是 POSIX 风格(<semaphore.h> ) 或 SysV 风格 (<sys/sem.h>):

[T]the semaphore lock operation shall cause the calling thread to be blocked and added to the set of threads awaiting the semaphore

关于你说的"unnamed semaphores are either thread- or process-related, but not both",我不太明白你的意思。如果分配在共享内存和 explicitly initialized as "pshared" 中,则未命名信号量可以在(父子)进程之间 共享 。但是,无论是否共享进程,未命名的信号量都会同步各个线程。

(就其价值而言,POSIX 互斥量也可能 be shared between processes。)