简体   繁体   English

sem_post / sem_wait是否明显快于pthread_mutex_lock / pthread_mutex_unlock?

[英]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. 我有一段需要快速运行的代码,现在我正在使用pthread_mutex_lock/pthread_mutex_unlock来同步线程,但我发现它对性能有一定的影响。 I was wandering, if anyone ever benchmarked this, is sem_post/sem_wait significantly faster than pthread_mutex_lock/pthread_mutex_unlock ? 我徘徊,如果有人对此进行基准测试, sem_post/sem_wait 明显快于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. 话虽如此,POSIX信号量确实有一个 ,并且就我而言只有一个 ,优于更复杂的原语,如互斥和条件变量: sem_post需要是异步信号安全的。 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. - 如果没有像管道或SysV IPC这样的重量较大的工具,这些工具本身是不可能的,这些工具与性能导向的pthread习语不能很好地交互。

Edit: For reference, the simplest implementation of pthread_mutex_trylock : 编辑:供参考, 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 : 以及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,这可能会更快,而且更加容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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