讀寫鎖的簡單示例

2021-09-06 20:06:12 字數 1890 閱讀 3299

/*

使用讀寫鎖實現四個執行緒讀寫一段程式的例項,共建立了四個新的執行緒,其中兩個執行緒用來讀取資料,另外兩個執行緒用來寫入資料。在任意時刻,如果有乙個執行緒在寫資料,將阻塞所有其他執行緒的任何操作。

*/#include

#include

#include

#include

#include

pthread_rwlock_t rwlock;

//讀寫鎖物件

int a=0

;void *thread_function_read_o(void *arg);//

讀執行緒1

void *thread_function_read_t(void *arg);//

讀執行緒2

void *thread_function_write_o(void *arg);//

寫執行緒1

void *thread_function_write_t(void *arg);//

寫執行緒2

int main(int argc,char *argv)

res = pthread_create(&a_thread, null, thread_function_read_o, null);//

create new thread建立執行緒

if (res != 0

)

res = pthread_create(&b_thread, null, thread_function_read_t, null);//

create new thread

if (res != 0

)

res = pthread_create(&c_thread, null, thread_function_write_o, null);//

create new thread

if (res != 0

)

res = pthread_create(&d_thread, null, thread_function_write_t, null);//

create new thread

if (res != 0

)

res = pthread_join(a_thread, &thread_result);//

等待a_thread執行緒結束

if (res != 0

)

res = pthread_join(b_thread, &thread_result);

if (res != 0

)

res = pthread_join(c_thread, &thread_result);

if (res != 0

)

res = pthread_join(d_thread, &thread_result);

if (res != 0

)

res = pthread_rwlock_destroy(&rwlock);//

銷毀讀寫鎖

if (res != 0

)

}void *thread_function_read_o(void *arg)

void *thread_function_read_t(void *arg)

void *thread_function_write_o(void *arg)

void *thread_function_write_t(void *arg)

程式中加的sleep僅僅是為了驗證,同一時間只能有乙個執行緒可以獲取寫入鎖,但是可以有多個讀者可以獲取讀取鎖!

讀寫鎖的簡單運用

與互斥鎖定相比,讀 寫鎖定允許對共享資料進行更高階別的併發訪問。雖然一次只有乙個執行緒 writer 執行緒 可以修改共享資料,但在許多情況下,任何數量的執行緒可以同時讀取共享資料 reader 執行緒 讀 寫鎖定利用了這一點。從理論上講,與互斥鎖定相比,使用讀 寫鎖定所允許的併發性增強將帶來更大的...

Linux 互斥鎖 讀寫鎖 條件變數簡單認識

執行緒同步 協調同步,對公共區域資料按序訪問,防止資料混亂,產生於時間有關的錯誤 鎖的使用 對公共資料進行保護,所有執行緒 應該 在訪問公共資料前先拿到鎖再訪問,但鎖本身不具備強制性 mutex的主要應用函式 pthread mutex init初始化 pthread mutex destory銷毀...

asyncio乙個簡單的鎖示例

import asyncio import time import logging logging.basicconfig 用日誌列印輸出資訊 level logging.info,format asctime s process d thread d message s async defmywo...