问题描述
对于诸如计数器之类的简单事物,如果有多个线程将增加数量.我读到互斥锁会降低效率,因为线程必须等待.因此,对我来说,原子计数器将是最有效的,但我从内部了解到它基本上是锁吗?所以我想我很困惑,哪一个比另一个更有效.
For something simple like a counter if multiple threads will be increasing the number. I read that mutex locks can decrease efficiency since the threads have to wait. So, to me, an atomic counter would be the most efficient, but I read that internally it is basically a lock? So I guess I'm confused how either could be more efficient than the other.
推荐答案
如果您有一个支持原子操作的计数器,它将比互斥锁更有效.
If you have a counter for which atomic operations are supported, it will be more efficient than a mutex.
从技术上讲,原子将在大多数平台上锁定内存总线.但是,有两个改善的细节:
Technically, the atomic will lock the memory bus on most platforms. However, there are two ameliorating details:
- 不可能在内存总线锁定期间挂起线程,但是可以在互斥锁锁定期间挂起线程.这就是让您获得无锁保证的原因(它没有说不锁,它只是保证至少有一个线程取得了进展).
- 最终,互斥体最终被原子实现.由于您至少需要一个原子操作来锁定一个互斥锁,并且需要一个原子操作来解锁一个互斥锁,所以即使在最好的情况下,至少要花两倍的时间才能进行互斥锁.
这篇关于基本互斥锁或原子整数哪个更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!