Linux 同步機制 讀寫鎖

2021-07-25 19:46:53 字數 2177 閱讀 5729

讀寫鎖也叫 shared-exclusive 鎖, 也是一種同步機制。讀寫鎖有三種狀態:讀模式下加鎖,寫模式下加鎖,不加鎖。有如下的使用約定:

讀模式共享,寫模式獨佔,適合讀頻率遠大於寫頻率的場景。

這些api位於 pthread.h 下。

/* initialize read-write lock rwlock using attributes attr, or use

the default values if later is null. */

extern

int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,

const pthread_rwlockattr_t *__restrict

__attr) __throw __nonnull ((1));

/* destroy read-write lock rwlock. */

extern

int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock)

__throw __nonnull ((1));

/* initialize attribute object attr with default values. */

extern

int pthread_rwlockattr_init (pthread_rwlockattr_t *__attr)

__throw __nonnull ((1));

/* destroy attribute object attr. */

extern

int pthread_rwlockattr_destroy (pthread_rwlockattr_t *__attr)

__throw __nonnull ((1));

/* acquire read lock for rwlock.  */

extern

int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)

__thrownl __nonnull ((1));

/* acquire write lock for rwlock. */

extern

int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)

__thrownl __nonnull ((1));

非阻塞模式加鎖,介面中含try,如果未獲取到,不阻塞執行緒,返回非零錯誤碼。被占用是ebusy, 可參考 linux man:pthread_rwlock_tryrdlock。

/* try to acquire read lock for rwlock.  */

extern

int pthread_rwlock_tryrdlock (pthread_rwlock_t *__rwlock)

__thrownl __nonnull ((1));

/* try to acquire write lock for rwlock. */

extern

int pthread_rwlock_trywrlock (pthread_rwlock_t *__rwlock)

__thrownl __nonnull ((1));

/* unlock rwlock.  */

extern

int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)

__thrownl __nonnull ((1));

編譯的時候記得連線pthread,gcc main.c -lpthread

#include 

#include

#include

char buff[100];

pthread_rwlock_t rwlock;

void* th_writer(void *p)

void* th_reader1(void *p)

void* th_reader2(void *p)

int main()

同步機制 「讀寫鎖「的實現

同步機制 讀寫鎖 pj.courtois,f.heymans,and d.l.parnas mble research laboratory brussels,belgium 多程序同時訪問臨界區域 critical section 的問題可以看成兩類程序 讀者 readers 和寫者 writer...

(4 3)Linux執行緒同步機制 讀寫鎖

1 問題描述 2 互斥關係 3 同步關係 1 在保證互斥的基礎上,linux 提供了對臨界資源訪問控制粒度更細的讀寫鎖機制 2 讀寫鎖機制可以實現如下訪問控制規則 3 讀寫鎖的操作與互斥量的操作非常類似 4 讀寫鎖的加鎖操作在互斥量加鎖的基礎上擴充套件,具有加讀鎖和加寫鎖兩種操作 標頭檔案 pthr...

核心同步機制之自旋鎖 讀 寫鎖

自旋鎖 spin lock 是用來在多處理器環境中工作的一種特殊的鎖。如果核心控制路徑發現自旋鎖 開著 就獲取鎖並繼續自己的執行。相反,如果核心控制路徑發現由執行在另乙個cpu上的核心控制路徑 鎖著 就在一直迴圈等待,反覆執行一條緊湊的迴圈指令,直到鎖被釋放。自旋鎖與互斥鎖有點類似,只是自旋鎖不會引...