哪个更有效,基本互斥锁或原子整数? [英] Which is more efficient, basic mutex lock or atomic integer?

查看:30
本文介绍了哪个更有效,基本互斥锁或原子整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于像计数器这样简单的东西,如果多个线程将增加数量.我读到互斥锁会降低效率,因为线程必须等待.所以,对我来说,原子计数器是最有效的,但我在内部读到它基本上是一个锁?所以我想我很困惑如何才能比另一个更有效率.

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.

推荐答案

原子操作利用处理器支持(比较和交换指令)并且根本不使用锁,而锁更依赖于操作系统并且执行不同,例如例如,Win 和 Linux.

Atomic operations leverage processor support (compare and swap instructions) and don't use locks at all, whereas locks are more OS-dependent and perform differently on, for example, Win and Linux.

锁实际上会暂停线程执行,为其他任务释放 CPU 资源,但在停止/重新启动线程时会产生明显的上下文切换开销.相反,尝试原子操作的线程不会等待并一直尝试直到成功(所谓的忙等待),因此它们不会产生上下文切换开销,也不会释放 cpu 资源.

Locks actually suspend thread execution, freeing up cpu resources for other tasks, but incurring in obvious context-switching overhead when stopping/restarting the thread. On the contrary, threads attempting atomic operations don't wait and keep trying until success (so-called busy-waiting), so they don't incur in context-switching overhead, but neither free up cpu resources.

总而言之,如果线程之间的争用足够低,通常原子操作会更快.您绝对应该进行基准测试,因为没有其他可靠的方法可以了解上下文切换和忙等待之间的最低开销是多少.

Summing up, in general atomic operations are faster if contention between threads is sufficiently low. You should definitely do benchmarking as there's no other reliable method of knowing what's the lowest overhead between context-switching and busy-waiting.

这篇关于哪个更有效,基本互斥锁或原子整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆