内核同步机制API之read_seqbegin

本文解析了Seqlock(一种写优先的锁)的工作原理及其读顺序锁的实现细节。通过具体的例程代码展示了如何在读操作中避免冲突,并保持写操作的优先级。

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

seqlock所示一种写优先的锁。其分为读顺序锁和写顺序锁。但是写优先。
其读顺序锁的例程如下:
static inline int grow_chain32(struct ufs_inode_info *ufsi,
			       struct buffer_head *bh, __fs32 *v,
			       Indirect *from, Indirect *to)
{
	Indirect *p;
	unsigned seq;
	to->bh = bh;
	do {
		seq = read_seqbegin(&ufsi->meta_lock);
		to->key32 = *(__fs32 *)(to->p = v);
		for (p = from; p <= to && p->key32 == *(__fs32 *)p->p; p++)
			;
	} while (read_seqretry(&ufsi->meta_lock, seq));
	return (p > to);
}
其源码分析如下:
可以看到这个函数没实现为内联函数
static inline unsigned read_seqbegin(const seqlock_t *sl)
{
	return read_seqcount_begin(&sl->seqcount);
}
static inline unsigned read_seqcount_begin(const seqcount_t *s)
{
	#没有定义CONFIG_DEBUG_LOCK_ALLOC的时候为空函数
	seqcount_lockdep_reader_access(s);
	return raw_read_seqcount_begin(s);
}
static inline unsigned raw_read_seqcount_begin(const seqcount_t *s)
{
	#开始一个seq-read的critical section,without barrier
	unsigned ret = __read_seqcount_begin(s);
	#内存barrier 
	smp_rmb();
	return ret;
}

static inline unsigned __read_seqcount_begin(const seqcount_t *s)
{
	unsigned ret;

repeat:
	#这里尝试从读取s->sequence的值,如果其返回为1的话,则说明可能正在写,则读尝试继续读取。
	#从这里可以很明显的看到顺序锁是写优先的。因为如果读获取不到锁的话,会一直等待,直到写释放锁.
	ret = READ_ONCE(s->sequence);
	if (unlikely(ret & 1)) {
		cpu_relax();
		goto repeat;
	}
	return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值