semaphores between processes

Jilles Tjoelker jilles at stack.nl
Thu Oct 22 21:47:35 UTC 2009


On Thu, Oct 22, 2009 at 04:08:11PM -0400, Andrew Gallatin wrote:
> We then moved on to posix semaphores.  Using sem_wait/sem_post
> with the sem_t residing in a shared page seems to work on
> all 3 platforms.  However, the FreeBSD (7-stable) man page
> for sem_init(3) has this scary text regarding the pshared
> value:

>       The sem_init() function initializes the unnamed semaphore pointed 
> to by
>       sem to have the value value.  A non-zero value for pshared specifies a
>       shared semaphore that can be used by multiple processes, which this
>       implementation is not capable of.

> Is this text obsolete?  Or is my test just "getting lucky"?

They work, but only if the processes are related and do not exec and the
parent process initializes the semaphores before forking. This is
because sem_t is a pointer to a malloc'ed structure. For process-shared
semaphores this really only contains an identifier of the kernel
semaphore. This also means process-shared semaphores are slower than
in-process semaphores (libthr implements those using atomics and umtx so
that system calls are only needed if a thread needs to sleep or be
awakened).

This is documented in comments in the source code, but not in man pages
or other documentation.

> Is there recommended way to do this?

Apart from sysv semaphores, perhaps posix named semaphores (sem_open()
etc). These require a 'kldload sem' on older versions though.

-- 
Jilles Tjoelker


More information about the freebsd-hackers mailing list