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
",index);
    
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 1
");

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

    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
",index);
    i++;
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 2
");

    

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

    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
",index);
    
    //pthread_mutex_unlock(&mutex);never unlock
    }
    else
    printf("con not get lock in thread 3
");
    i++;

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 3
");
        
        
    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
",index);
    
    }
    //pthread_mutex_unlock(&mutex);never unlock
    else
    printf("con not get lock in thread 4
");

    if(pthread_rwlock_trywrlock(&rwlock)==EBUSY)
        printf("con not write in thread 4
");
        
    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);



}
原文地址:https://www.cnblogs.com/wzben/p/5432518.html