一、RCU 模式下更新链表项 list_replace_rcu 函数



在 Linux 源码 linux-5.6.18\include\linux\rculist.h 头文件中定义的就是 RCU 链表的操作 ,

其中定义的

static inline void list_replace_rcu(struct list_head *old,
				struct list_head *new)

函数 , 就是 更新 链表元素 的 函数 ;


list_replace_rcu 函数中 , 更新链表元素的核心操作就是将 被更新的 链表元素 , 前后指针指向新的元素即可 ;

	new->next = old->next;
	new->prev = old->prev;
	rcu_assign_pointer(list_next_rcu(new->prev), new);
	new->next->prev = new;
	old->prev = LIST_POISON2;

list_replace_rcu 函数原型 :

/**
 * list_replace_rcu - replace old entry by new one
 * @old : the element to be replaced
 * @new : the new element to insert
 *
 * The @old entry will be replaced with the @new entry atomically.
 * Note: @old should not be empty.
 */
static inline void list_replace_rcu(struct list_head *old,
				struct list_head *new)
{
	new->next = old->next;
	new->prev = old->prev;
	rcu_assign_pointer(list_next_rcu(new->prev), new);
	new->next->prev = new;
	old->prev = LIST_POISON2;
}

在这里插入图片描述

源码路径 : linux-5.6.18\include\linux\rculist.h#198





二、链表操作时使用 smp_wmb() 函数保证代码执行顺序



编译器 和 CPU 优化 代码时 , 有时会将 代码执行顺序改变 ,

在链表操作时 , 代码的执行顺序必须得到保证 , 否则会得到不可预知的结果 ;

使用 smp_wmb() 函数 , 可以保证该函数 前两行 的代码 执行完毕后 , 再执行后两行的代码 ;

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐