Amongst many others, OS X has the following synchronization primitives:
- Named POSIX semaphores
- pthread condition variables
- Mach Semaphores
Unnamed POSIX Semaphores (sem_init()) are not supported (the function is defined in the header but calling it returns ENOSYS).
Named POSIX semaphores and condition variables are implemented internally using Mach semaphores which in their own right are virtually undocumented apart from a few functions which you can find manpages for in the XNU source code under osfmk/man.
The relevant functions are defined in mach/semaphore.h.
The implementations of pthread condition variables and POSIX semaphores are publicly visible as part of the open source XNU code and are pretty clean, it’s really nice to see how those are implemented behind the scenes.
One more tidbit is that if a thread is waiting on a Mach semaphore, then sending a signal to that thread via pthread_kill() will cause semaphore_wait() to exit (with an error code). I’m not sure if the semaphore will remain in a consistent state in this case, I’m merely mentioning that for future reference.
Mach semaphores are counting semaphores, unlike named POSIX semaphores they are reference counted and will go away if your process dies (rather than being allocated in a kernel table and staying around indefinitely). AFAIK Apple considers Mach semaphores an SPI [private] and therefore either the API or it’s internal behavior may change between arbitrary system releases so caveat emptor.

Post a Comment