linux讀寫鎖


讀寫鎖是一個可以分寫狀態和讀狀態的鎖,可以分別加上寫狀態或讀狀態的鎖。在讀模式的鎖下,所有試圖以讀模式獲得它進行加鎖的線程都可以獲得鎖,所有希望以寫模式獲得它的都會被阻塞。在寫模式下,讀寫鎖都被阻塞。讀寫鎖又成共享互斥鎖。

簡單的說,讀模式的加鎖下,所有進程都可以獲得讀鎖,但都不能獲得寫鎖。

在寫模式下,讀寫鎖就變成了互斥鎖,只有一個線程可以獲得鎖。

 

例子:

4個線程,全都加鎖,不釋放鎖。

 

1、互斥鎖:

 

在線程4獲得鎖后,由於不釋放鎖,所以后續的進程都得不到鎖。

 

2、4個進程加上讀鎖

 

 

由於讀鎖是共享的,所以就算不釋放讀鎖,每個進程都能獲得該鎖。

同時,再加上讀鎖的同時,是不可以寫操作的,就是說不能獲取寫模式。

 

#include <pthread.h>  
#include <semaphore.h>
#include <unistd.h>  
#include <stdio.h>
#include<fcntl.h>
#include <pthread.h>
#include <errno.h>

int index = 1;

pthread_rwlock_t rwlock;
pthread_mutex_t mutex;

void fun1(void){

    int i = 0;
    while(i<50){

    //if(pthread_mutex_trylock(&mutex)==0){
    if(pthread_rwlock_tryrdlock(&rwlock)==0){
    printf("In thread 1,lock,index is %d\n",index);
    
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 1\n");

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 1\n");

    i++;
    usleep(100);

    }


}

void fun2(void){

    int i = 0;
    while(i<50){

    //if(pthread_mutex_trylock(&mutex)==0){
    if(pthread_rwlock_tryrdlock(&rwlock)==0){
    printf("In thread 2,lock,index is %d\n",index);
    i++;
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 2\n");

    

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 2\n");

    i++;
    usleep(100);

    }


}


void fun3(void){

    int i = 0;
    while(i<50){

    //if(pthread_mutex_trylock(&mutex)==0){
    if(pthread_rwlock_tryrdlock(&rwlock)==0){
    printf("In thread 3,lock,index is %d\n",index);
    
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 3\n");
    i++;

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 3\n");
        
        
    usleep(100);

    }


}



void fun4(void){

    int i = 0;
    while(i<50){

    //if(pthread_mutex_trylock(&mutex)==0){
    if(pthread_rwlock_tryrdlock(&rwlock)==0){
    printf("In thread 4,lock,index is %d\n",index);
    
    }
    //pthread_mutex_unlock(&mutex);never unlock
    else
    printf("con not get lock in thread 4\n");

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 4\n");
        
    i++;
    usleep(100);

    }


}

int main(){

    pthread_t tid1,tid2,tid3,tid4;

    pthread_mutex_init(&mutex,NULL);
    
    pthread_create(&tid1,NULL,(void*)fun1,NULL);
    pthread_create(&tid2,NULL,(void*)fun2,NULL);
    pthread_create(&tid3,NULL,(void*)fun3,NULL);
    pthread_create(&tid4,NULL,(void*)fun4,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    pthread_join(tid4,NULL);



}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM