views:

1837

answers:

4

I am trying to port a project (from linux) that uses Semaphores to Mac OS X however some of the posix semaphores are not implemented on Mac OS X

The one that I hit in this port is sem_timedwait()

I don't know much about semaphores but from the man pages sem_wait() seems to be close to sem_timedwait and it is implemented

From the man pages

sem_timedwait() function shall lock the semaphore referenced by
sem as in the sem_wait() function. However, if the semaphore cannot be
locked without waiting for another process or thread to unlock the
semaphore by performing a sem_post() function, this wait shall be ter-
minated when the specified timeout expires

From my limited understanding of how semphores work I can see that sem_timedwait() is safer, but I still should be able to use sem_wait()

Is this correct? If not what other alternatives do I have...

Thanks

A: 

Could you try to mimic the functionality of the sem_timedwait() call by starting a timer in another thread that calls sem_post() after the timer expires if it hasn't been called by the primary thread that is supposed to call sem_post()?

stinkymatt
+2  A: 

It's likely that the timeout is important to the operation of the algorithm. Therefore just using sem_wait() might not work.

You could use sem_trywait(), which returns right away in all cases. You can then loop, and use a sleep interval that you choose, each time decrementing the total timeout until you either run out of timeout or the semaphore is acquired.

A much better solution is to rewrite the algorithm to use a condition variable, and then you can use pthread_cond_timedwait() to get the appropriate timeout.

Jared Oberhaus
A loop with trywait with a sleep will not work since a process would lose its position in the queue every time. If lots of threads or processes are trying to lock one semaphore some of them would always hit it when it is locked and thus timeout.A busy loop might work, but it is not a solution.
Eugene
+2  A: 

Have you considered using the apache portable runtime? It's preinstalled on every Mac OS X Box and many Linux distros and it comes with a platform neutral wrapper around thread concurrency, that works even on MS Windows:

http://apr.apache.org/docs/apr/1.3/group__apr__thread__cond.html

Greets Seb

flitzwald
A: 

If you can just use MP API:
- MPCreateSemaphore/MPDeleteSemaphore
- MPSignalSemaphore/MPWaitOnSemaphore

MPWaitOnSemaphore exists with kMPTimeoutErr if specified timeout is exceeded without signaling.

Valda