# Semaphores (and alternatives)



## davidbrit2 (Feb 10, 2005)

So apparently OS X doesn't support semaphores, despite providing fully formed header files for the API. Yeah, okay, whatever, that makes a hell of a lot of sense. I do so love mysterious run-time errors instead of straight-forward compiler errors.

Anyway, what's the simplest way of getting a small threaded program using the basic sem_init(), sem_wait(), and sem_post() stuff to work on OS X? I saw some references to using the Carbon API and corresponding MP calls, but it was a little sparse on implementation details.


----------



## lurk (Feb 10, 2005)

This is stolen from here http://www.cocoabuilder.com/archive/message/cocoa/2004/7/3/110908

_Unnamed POSIX semaphores are indeed not implemented. Semaphores are 
implemented on top of mach semaphores, so that probably ties into the 
reasoning. You must create a named semaphore via sem_open(). You'll 
have to pass the semaphore name into sem_unlink() as well. Named POSIX 
semaphores work wonderfully well on MacOS X, but you do have to do a 
little extra management with the semaphore names. I recommend filing a 
feature request for unnamed POSIX semaphore support._

Hope that helps.


----------



## davidbrit2 (Feb 10, 2005)

Okay, I guess that explains the presence of the SysV/POSIX semaphore headers. Still kind of weird though.

I dug around the Apple Developer site a bit and found some API details for Mach kernel semaphores. (Here, if anybody wants it.) It works, but kind of uglies up the source code with a bunch of #if defined(__APPLE__) cross platform compilation junk. And it seems that calling  semaphore_signal() immediately yields the thread, similar to using a mutex. Strange...


----------



## lurk (Feb 10, 2005)

You can still use the Posix semaphores, just not anonymous ones.  The named variety are portable and there is no need to go all the way down to Mach.


----------



## davidbrit2 (Feb 10, 2005)

lurk said:
			
		

> and there is no need to go all the way down to Mach.



Too late. ;-) You just have to include mach/task.h and mach/semaphore.h, and then the semaphore system calls seem to be almost identical to POSIX ones (but with different symbols, of course). So this will do for now, since it's all experimental junk I'm messing with anyway.


----------

