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.

 

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