Linux系統程式設計讀寫鎖和條件變數使用

2021-10-05 12:51:00 字數 2939 閱讀 4344

linux系統程式設計讀寫鎖和條件變數使用

文章目錄

1.讀寫鎖概念

2.條件變數的概念和使用

1.讀寫鎖概念

1.讀寫鎖的適用場景?

互斥鎖- - -讀寫序列

讀寫鎖- - -:

讀: 並行

寫:序列

程式中的讀操作大於寫操作的時候

2.**展示

建立三個寫執行緒,建立五個讀執行緒

為了防止資料混亂(cpu排程問題)

需要給共享資源上鎖,保證資料的整齊

使用讀寫鎖

#include

#include

#include

#include

#include

int number=0;

//建立讀寫鎖

pthread_rwlock_t lock;

void* write_func(void* arg)

return null;

}void* read_func(void* arg)

return null;

}int main()

//建立五個度執行緒

int j=0;

for(j=3;j<8;++j)

//阻塞**子執行緒的pcb

i=0;

for(i=0;i<8;++i)

//釋放讀寫鎖資源

pthread_rwlock_destroy(&lock);

return 0;}1

2345

6789

1011

1213

1415

1617

1819

2021

2223

2425

2627

2829

3031

3233

3435

3637

3839

4041

4243

4445

4647

4849

5051

5253

5455

5657

2.條件變數的概念和使用

1.條件變數的兩個動作

條件不滿足,阻塞執行緒

當條件滿足,通知阻塞的執行緒開始工作

條件變數的型別

1. pthread_cond_t cond;

主要函式

①初始化乙個條件變數–condition;

1. pthread_cond_init(pthread_cond_t* restrict cond,

const pthread_condattr_t* restrict attr);12

②銷毀乙個條件變數

1. pthread_cond_destroy(pthread_cond_t* cond);

③阻塞等待乙個條件變數

1. pthread_cond_wait(pthread_cond_t* restrict cond,

pthread_mutex_t* restrict mutex);12

阻塞執行緒

將已經上鎖的mutex解鎖

該函式解除阻塞,會對互斥鎖加鎖

④限時等待乙個條件變數—阻塞一定的時長

1. pthread_cond_timedwait(pthread_cond_t* restrict cond,

pthread_mutex_t* restrict mutex,

const struct timespaec *restrict abstime);12

3⑤喚醒至少乙個阻塞在條件變數上的執行緒

1. pthread_cont_signal(pthread_cond_t* cond);

⑥喚醒全部阻塞在條件變數上的執行緒

1. pthread_cond_broadcast(pathread_cond_t* cond);

**展示

條件變數的使用常常會搭配著互斥鎖一起使用

互斥鎖- - - - -保護共享資源

條件變數- - - - 對執行緒的阻塞作用(條件不滿足則阻塞,條件滿足則不再阻塞)

#include

#include

#include

#include

#include

#include

//--------------------------全域性引數設定-----------------------

//建立結點結構

typedef struct node node;

//定義指向鍊錶頭部的指標

node* head=null;

//執行緒同步---互斥鎖

pthread_mutex_t mutex;

//阻塞執行緒

pthread_cond_t cond;

//--------------------------生產者操作----------------------

void* wr_func(void* arg)

return null;

}//---------------------消費者操作---------------------

void* rd_func(void* arg)

//鍊錶不為空

//產生消費行為,刪除頭結點

node* pple=head;

head=head->next;

printf("-----消費者: %lu,%d\n",pthread_self(),pple->data);

free(pple);

pthread_mutex_unlock(&mutex);

}return null;

}//---------------------------main函式主函式----------------------------

int main()

Linux系統程式設計 讀寫鎖rwlock

讀寫鎖是另一種實現執行緒間同步的方式。與互斥量類似,但讀寫鎖將操作分為讀 寫兩種方式,可以多個執行緒同時占用讀模式的讀寫鎖,這樣使得讀寫鎖具有更高的並行性。讀寫鎖的特性為 寫獨佔,讀共享 寫鎖優先順序高。對於讀寫鎖,掌握了這12個字就足矣了。linux環境下,讀寫鎖具有以下三種狀態 讀模式下加鎖狀態...

Linux系統程式設計 讀寫鎖rwlock

讀寫鎖是另一種實現執行緒間同步的方式。與互斥量類似,但讀寫鎖將操作分為讀 寫兩種方式,可以多個執行緒同時占用讀模式的讀寫鎖,這樣使得讀寫鎖具有更高的並行性。讀寫鎖的特性為 寫獨佔,讀共享 寫鎖優先順序高。對於讀寫鎖,掌握了這12個字就足矣了。linux環境下,讀寫鎖具有以下三種狀態 1.讀模式下加鎖...

Linux系統程式設計 條件變數

條件變數是用來等待執行緒而不是上鎖的,條件變數通常和互斥鎖一起使用。條件變數之所以要和互斥鎖一起使用,主要是因為互斥鎖的乙個明顯的特點就是它只有兩種狀態 鎖定和非鎖定,而條件變數可以通過允許執行緒阻塞和等待另乙個執行緒傳送訊號來彌補互斥鎖的不足,所以互斥鎖和條件變數通常一起使用。當條件滿足的時候,執...