Linux内核深度解析之内核互斥技术——读写信号量

读写信号量

读写信号量是对互斥信号量的改进,允许多个读者同时进入临界区,读者和写者互斥,写者和写者互斥,适合在以读为主的情况下使用。

读写信号量的定义:

复制代码
include/linux/rwsem.h
struct rw_semaphore {
    atomic_long_t count;
    struct list_head wait_list;
    raw_spinlock_t wait_lock;
#ifdef CONFIG_RWSEM_SPIN_ON_OWNER
    struct optimistic_spin_queue osq; /* spinner MCS lock */
    /*
     * Write owner. Used as a speculative check to see
     * if the owner is running on the cpu.
     */
    struct task_struct *owner;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
    struct lockdep_map    dep_map;
#endif
};
复制代码

 

初始化静态读写信号量的方法:

DECLARE_RWSEM(name)

在运行时动态初始化读写信号量的方法:

init_rwsem(sem)

申请读锁的函数:

(1)申请读锁,如果写者占有写锁或者正在等待写锁,那么进程深度睡眠

void down_read(struct rw_semaphore *sem);

(2)申请读锁,如果写者占有写锁或者正在等待写锁,那么进程中度睡眠

int down_read_killable(struct rw_semaphore *sem);

(3)尝试申请读锁,不会等待。如果申请成功,返回1;否则返回0。

int down_read_trylock(struct rw_semaphore *sem);

释放读锁的函数:

void up_read(struct rw_semaphore *sem);

申请写锁的函数:

(1)申请写锁,如果写者占有写锁或者读者占有读锁,那么进程深度睡眠

void down_write(struct rw_semaphore *sem);

(2)申请写锁,如果写者占有写锁或者读者占有读锁,那么进程中度睡眠

int down_write_killable(struct rw_semaphore *sem);

(3)尝试申请写锁,不会等待。如果申请成功,返回1;否则返回0

int down_write_trylock(struct rw_semaphore *sem);

占有写锁以后,把写锁降级为读锁的函数:

void downgrade_write(struct rw_semaphore *sem);

释放写锁的函数:

void up_write(struct rw_semaphore *sem);

from:
https://www.codeleading.com/article/87593997601/

posted @   aspirs  阅读(697)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示