Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核同步機制:原子操作與自旋鎖

Linux 內核在處理多執行緒與中斷環境時,需要同步機制避免資料競爭。本文介紹原子操作與自旋鎖的基本概念。

原子操作

原子操作是不可分割的指令,常見型別為 atomic_t,本質上是整數。可用 atomic_set、atomic_add、atomic_inc 與 atomic_dec_and_test 等操作。

自旋鎖

自旋鎖若已被持有,執行緒會忙等待直到鎖可用。可透過 SPIN_LOCK_UNLOCKED、spin_lock_init 或 DEFINE_SPINLOCK 初始化。

使用時通常為 spin_lock 與 spin_unlock。若在中斷處理中使用,建議使用 spin_lock_irqsave 與 spin_unlock_irqrestore,先保存並關閉本地中斷,避免死鎖。

Copyright © Linux教程網 All Rights Reserved