信号量和互斥量,哪个更快?
如果考虑二进制信号量和互斥量,哪一个更快?我的意思是,需要更少的指令。与信号量相比,互斥量还维护哪些额外数据?
If you consider a binary semaphore and mutex, which one is faster? I mean, takes less instructions. What additional data does mutex maintain compared to semaphore?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于实现,但您可能会发现互斥体的实现速度稍快一些。互斥体通常通过测试和设置来实现,而信号量通常通过测试和增量来实现,或者作为保护增量变量的互斥体来实现。
我建议在大多数情况下使用互斥体,但不是因为速度;只是因为使用互斥锁编写的代码更容易理解,因为语义不太复杂。
This is implementation dependent, but you will probably find that mutex has been implemented to be slightly faster. Mutexes are typically implemented with test and set, while semaphores are often implemented with test and increment or as a mutex guarding a variable that is incremented.
I would suggest using a mutex in most cases, but not due to speed; simply because code written using mutexes is easier to understand as the semantics are less complicated.