15、操作系统——读写锁

目录

1、互斥锁的缺点

2、读写锁的优点

3、读写锁的操作步骤

4、API

(1)初始化/销毁读写锁(pthread_rwlock_destroy、pthread_rwlock_init)

 (2)阻塞添加读/写锁/非阻塞添加读/写锁/解锁

 5、代码

 6、注意事项

1、互斥锁的缺点

当程序资源大部分都是读操作,互斥锁会导致多个个线程在获取该资源是阻塞等 待, 导致程序的效率降低。

2、读写锁的优点

(1)读锁:在同一时间内允许有多个线程进行读取资源,可以同时添加多个读锁

(2)写锁:在同一个时间内只允许有一个线程进行读取资源, 不允许有其它线程持有锁资源

3、读写锁的操作步骤

(1) 初始化读写锁pthread_rwlock_init()

(2)添加读锁 / 写锁pthread_rwlock_rdlock / pthread_rwlock_wrlock

(3)当不再使用共享资源的时候解锁pthread_rwlock_unlock()

(4)当不需要使用读写锁时可以销毁pthread_rwlock_destroy()

4、API

(1)初始化/销毁读写锁(pthread_rwlock_destroy、pthread_rwlock_init)

 (2)阻塞添加读/写锁/非阻塞添加读/写锁/解锁

 5、代码

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

char * msg = NULL ;
pthread_rwlock_t rwlock ;

void * FUNC(void * arg )
{
    
    int num = (int ) arg ;
    // printf("num:%d\n" , num); 
    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("我是%d号线程,我看到的消息是:%s\n" , (int)arg , msg) ;
        pthread_rwlock_unlock(&rwlock);
        sleep(1);//刚好所有的读锁都睡觉了,就上写锁
    }
}

int main(int argc, char const *argv[])
{
    msg = calloc(128,1);
    
    // 初始化锁资源
    pthread_rwlock_init(&rwlock, NULL );
    
    // 创建多个线程
    pthread_t thread1 ;
    pthread_t thread2 ;
    pthread_t thread3 ;
    pthread_t thread4 ;
    pthread_t thread5 ;
    pthread_t thread6 ;
    
    pthread_create(&thread1, NULL, FUNC , (void *)1 ); 
    pthread_create(&thread2, NULL, FUNC , (void *)2 ); 
    pthread_create(&thread3, NULL, FUNC , (void *)3 ); 
    pthread_create(&thread4, NULL, FUNC , (void *)4 ); 
    pthread_create(&thread5, NULL, FUNC , (void *)5 ); 
    pthread_create(&thread6, NULL, FUNC , (void *)6 ); 
    

    while (1)
    {
        // 申请上写锁 --> 写锁在同一时间内只允许上一个
        printf("等待上写锁.....\n");
        pthread_rwlock_wrlock(&rwlock);
        printf("成功获得写锁.....\n");
        fgets(msg , 128 , stdin) ;
        pthread_rwlock_unlock(&rwlock);
        printf("解除写锁状态.....\n");
        sleep(5);
    }
    

    
    return 0;
}

6、注意事项

 不管是读锁还是写锁,在加锁的时候都需要判断当前共享资源的状态;

读锁:线程读取信息时,先检查写锁是否存在,若存在则等待,否则添加读锁

写锁:线程写入信息时,检查是否有人读取,若有则等待,否则添加写锁

猜你喜欢

转载自blog.csdn.net/weixin_45981798/article/details/129884074
今日推荐