简体   繁体   中英

Is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock?

I have a block of code that needs to run fast, right now I'm using pthread_mutex_lock/pthread_mutex_unlock to sync the threads but I saw that it has a certain impact on performance. I was wandering, if anyone ever benchmarked this, is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock ?

Thanks!

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'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.

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.

如果您正在使用Objective C,那么您的环境可能足够接近Cocoa,以便能够使用Grand Central Dispatch,这可能会更快,而且更加容易

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM