linux系統編程:線程同步-讀寫鎖(rwlock),linuxrwlock

來源:互聯網
上載者:User

linux系統編程:線程同步-讀寫鎖(rwlock),linuxrwlock

                              線程同步-讀寫鎖(rwlock)

讀寫鎖

讀寫鎖是互斥量的細化:顯然,只有對全域資然進行寫入操作時,才需要同步;在對全域資然進行讀取操作時,是不需要鎖的。


相關函數
pthread_rwlock_t    //讀寫鎖類型pthread_rwlock_init //初始化pthread_rwlock_destroy  //銷毀鎖pthread_rwlock_rdlock   //擷取讀鎖pthread_rwlock_wrlock   //擷取寫鎖pthread_rwlock_tryrdlockpthread_rwlock_trywrlockpthread_rwlock_unlock   //釋放讀寫鎖
    

樣本

#include <stdio.h>#include <unistd.h>#include <pthread.h>pthread_rwlock_t rwlock;int counter = 0;void *fun_r(void *argv){while (1){//既然是讀操作,當然可以完全不用鎖pthread_rwlock_rdlock(&rwlock);printf("thread %x read,counter=%d\n", pthread_self(), counter);pthread_rwlock_unlock(&rwlock);sleep(1);}}void *fun_w(void *argv){while (1){//寫操作,寫操作使用寫鎖pthread_rwlock_wrlock(&rwlock);counter++;printf("thread %x write,counter=%d\n", pthread_self(), counter);pthread_rwlock_unlock(&rwlock);sleep(1);}}int main(void){pthread_rwlock_init(&rwlock, NULL);pthread_t tid[5];int i;//開啟2個線程讀for (i = 0; i < 2; i++){pthread_create(&tid[i], NULL, fun_r, NULL);}//開啟3個線程寫for (i = 2; i < 5; i++){pthread_create(&tid[i], NULL, fun_w, NULL);}for (i = 0; i < 5; i++){pthread_join(tid[i], NULL);}pthread_rwlock_destroy(&rwlock);return 0;}

        



CCPP Blog 目錄

著作權聲明:本文為博主原創文章,轉載,請註明出處。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.