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);

猜你喜欢

转载自blog.csdn.net/linuxweiyh/article/details/106956653