Linux多线程编程-利用读写锁实现读写互斥

本文深入探讨了读写锁的工作原理,解释了为什么一次只有一个线程可以拥有写模式的读写锁,而多个线程可以同时拥有读模式的读写锁。通过分析读写锁在不同模式下对线程请求的处理方式,以及提供初始化、销毁和加锁解锁的代码示例,帮助读者理解读写锁如何提高并发性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

一次只有一个线程可以占有写模式的读写锁,但是可以有多个线程同时占有读模式的读写锁,正是因为这个特性,当读写锁是写加锁状态时,在这个锁被解锁之前, 所有试图对这个锁加锁的线程都会被阻塞。
通常,当读写锁处于读模式锁住状态时,如果有另外线程试图以写模式加锁,读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞。

相关知识

初始化操作:
pthread_rwlock_init(
pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr
);
销毁锁操作:
pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
成功则返回0,出错则返回错误编号

pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
这3个函数分别实现获取读锁, 获取写锁和释放锁的操作

实现代码

#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bits/pthreadtypes.h>
static pthread_rwlock_t rwlock; //读写锁对象
int count = 0;

void *thread_function_read(void *arg)
{
    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("***%ld, read count %d\n", pthread_self(), count);
        sleep(1);
        pthread_rwlock_unlock(&rwlock);
	    usleep(100);
    }
    return NULL;
}

void *thread_function_write(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock);
        count++;
        printf("***%ld, write count %d\n", pthread_self(), count);
        sleep(1);
        pthread_rwlock_unlock(&rwlock);
	    usleep(100);
    }
    return NULL;
}
 int main(int argc, char *argv[])
{
    pthread_t rpthread1, rpthread2, wpthread;
    pthread_rwlock_init(&rwlock,NULL);
    pthread_create(&rpthread1, NULL, thread_function_read, NULL);
    pthread_create(&rpthread2, NULL, thread_function_read, NULL);
    pthread_create(&wpthread, NULL, thread_function_write, NULL);
    pthread_join(rpthread1, NULL);           
    pthread_join(rpthread2, NULL);           
    pthread_join(wpthread, NULL);           
    pthread_rwlock_destroy(&rwlock);          
    return 0;
}

运行结果

***139633593894656, read count 0
***139633585501952, read count 0
***139633442891520, write count 1
***139633593894656, read count 1
***139633585501952, read count 1
.
.
.

最后

  • 由于博主水平有限,难免有疏漏之处,欢迎读者批评指正!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值