atomic和mutex

 

原子操作和锁的区别:

  • 原子操作比锁执行快,锁会产生上下文切换;原子操作理解成自旋锁;
  • 且仅当操作物理或者逻辑不可中断(不可中断:操作所涉内存不可被读取和修改)时,该操作才是原子的。
  • 原子操作一直占用cpu资源,一直等待条件满足;锁会释放CPU资源。

 

参考资料:

[1] 原子操作与锁

[2] 

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.

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.

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章