pthread 自旋鎖

自旋鎖 (Spin Lock) 與互斥量類似,但它並不會使得線程進入阻塞狀態,而是在獲得自旋鎖之前使線程處於忙等狀態 (aka, 自旋狀態)。那麼,自旋鎖存在的意義是什麼?

A spin lock could be used in situations where locks are held for short periods of times and threads don’t want to incur the cost of being descheduled.

如果線程調度的開銷比忙等的開銷要大,那麼顯然讓線程進入忙等狀態更有助於提高併發度。

API

相關數據結構:

  • pthread_spinlock_t : 自旋鎖數據結構;

init and destory

函數原型:

int pthread_spin_destroy(pthread_spinlock_t *lock);
int pthread_spin_init(pthread_spinlock_t *lock, int pshared);

初始化/銷燬自旋鎖 lockpshared 的取值及其描述如下:

  • PTHREAD_PROCESS_SHARED : 進程間共享自旋鎖(該鎖應當分配在共享內存上)。
  • PTHREAD_PROCESS_PRIVATE : 單個進程內共享。

lock/trylock/unlock

函數原型:

int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);

作用:

  • lock 申請自旋鎖, 在獲得鎖之前保持自旋狀態;
  • trylock 如果申請自旋鎖失敗,立即返回 EBUSY 錯誤(表示 Device or resource busy),也就是說,trylock 並不能使線程自旋;
  • unlock 釋放自旋鎖。

對已鎖定的自旋鎖再次調用 lock ,是一種未定義行爲(可能返回 EDEADLK 錯誤)。對未鎖定的自旋鎖調用 unlock 與之同理。

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