Thursday, November 17, 2011

if you are using sem_timedwait on iOS or Mac OS X ....

While porting some C/C++ code to iOS found out that sem_timedwait is not implemented on iOS or Mac OS X and seems like on many BSD systems. Here is the discussion on the topic:
http://stackoverflow.com/questions/641126/posix-semaphores-on-mac-os-x-sem-timedwait-alternative
The discussion a bit old but it seems like it is still a valid one.

For now I conditionally compiled the code with the call sem_wait, will look into a better cross-platform solution later.

4 comments:

roger said...

So what's your work around?

Alex said...

At this point in this particular project I just used sem_wait and made sure nobody leaves the locked semaphore forever. I didn't have time to look further into this yet. The first thought that comes in mind is to try to utilize the sem_trywait instead, create a wrapper that will handle locking and unlocking, if semaphore is locked wait for signal on condition. Every call to unlock on your wrapper API will signal condition, to allow items in the wait list to proceed. Also, in the event driven code you can utilize the main event loop to kick off the timestamps checks of items in the wait list and signal condition on the timeout. That's just a general idea, I might be wrong. I'll try to post my solution when I get back to this part of the project.

KeithS said...

I had this problem some time back. We have some code to be deployed on Linux that depends heavily on sam_timedwait(), and we wanted to be able to test it on OS X laptops. I ended up implementing a sam_timedwait() using a thread that interrupts a normal sem_wait() call after the timeout expires. It took a long time to get this basic idea working reliably, but in the end I have a piece of code that worked well enough for our purposes.

The code is available at

http://www.aao.gov.au/local/www/ks/uploads/sem_timedwait.c

You - and others - might find it useful, if only as something to build upon. Please note the copyright and slightly restrictive terms upon which I'm supposed to allow this stuff out, but mainly note that I make no claims for the reliability of the code at all. Use at own risk. Since this only had to work in a test environment and not on a production system its reliability requirements weren't crucially stringent, although it's worked well enough for us for a while now.

But I am surprised and disapointed that Apple don't support this call. It doesn't even seem to have made it into Lion; you would think they're smart enough to be able to make it work properly.

Alex said...

Thanks a lot KeithS!