I would expect them to be roughly the same speed, but you could always benchmark it yourself if you really care. With that said, POSIX semaphores do have one, and as far as I'm concerned only one, advantage over the more sophisticated primitives like mutexes and condition variables: sem_post
is required to be async-signal-safe. It is the only synchronization-related function which is async-signal-safe, and it makes it possible to perform minimal interaction between threads from a signal handler! - something which would otherwise be impossible without much heavier tools like pipes or SysV IPC which don't interact well with the performance-oriented pthread idioms.
Edit: For reference, the simplest implementation of pthread_mutex_trylock
:
if (mutex->type==PTHREAD_MUTEX_DEFAULT) return atomic_swap(mutex->lock, EBUSY);
else /* lots of stuff to do */
and the simplest implementation of sem_trywait
:
int val = sem->val;
return (val>0 && atomic_compare_and_swap(sem->val, val, val-1)==val) ? 0 : EAGAIN;
Assuming an optimal implementation, I would guess that a mutex lock might be slightly faster, but again, benchmark it.