Is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock? Is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock? unix unix

Is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock?


I'd say a semaphore is probably slower than a mutex because a semaphore has a superset of the mutex behavior. You can try something at user level such as spin lock that runs without kernel support, but it all depends on the rate of lock/unlocks and the contention.


No, it is not significantly faster. They are implemented using same lower level primitives (read spin-locks and system calls). The real answer though would only be comparing both in your particular situation.


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.