读写锁分为spinlock 类型和信号量类型
首先看spinlock类型
其中spinlock类型的读写锁定义在include/linux/rwlock_types.h
其结构定义如下:
typedef struct {
arch_rwlock_t raw_lock;
#ifdef CONFIG_DEBUG_SPINLOCK
unsigned int magic, owner_cpu;
void *owner;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map dep_map;
#endif
} rwlock_t;
可以看出出去debug的config 后rwlock_t就等于下面的结构
typedef struct {
arch_rwlock_t raw_lock;
} rwlock_t;
读写spinlock的API 都定义在include/linux/rwlock.h 中
例如在使用读写spinlock锁时候,首先初始化
# define rwlock_init(lock) \
do { \
static struct lock_class_key __key; \
\
__rwlock_init((lock), #lock, &__key); \
} while (0)
然后是读锁的lock 和 unlock
read_lock()
read_unlock()
其次是写锁的lock 和 unlock
write_lock()
write_unlock
剩下就是spinlock锁有的API在rwlock这边都会有,例如read_lock_irq/write_lock_irq等
其次是读写信号量锁
其定义在include/linux/rwsem.h中
#ifdef CONFIG_RWSEM_GENERIC_SPINLOCK
#include <linux/rwsem-spinlock.h> /* use a generic implementation */
#define __RWSEM_INIT_COUNT(name) .count = RWSEM_UNLOCKED_VALUE
#else
/* All arch specific implementations share the same struct */
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
};
其初始化为
#define init_rwsem(sem) \
do { \
static struct lock_class_key __key; \
\
__init_rwsem((sem), #sem, &__key); \
} while (0)
对应的读锁的lock和unlock
down_read ()
up_read()
写锁的lock和unlock
down_write()
up_write()
读写锁总结
最新推荐文章于 2022-05-19 15:13:57 发布
本文详细介绍了Linux系统中两种类型的读写锁:spinlock类型和信号量类型。spinlock类型的读写锁通过rwlock_t结构体实现,而信号量类型的读写锁则使用rw_semaphore结构体。文章还提供了这些锁的初始化、读锁、写锁及其解锁操作的具体方法。
摘要由CSDN通过智能技术生成