[Linux]学习笔记系列 -- hashtable


title: hashtable

categories:

  • linux
  • include
    tags:
  • linux
  • include
    abbrlink: 14dfa8ed
    date: 2025-10-03 09:01:49

https://github.com/wdfk-prog/linux-study

文章目录

  • include/linux/hashtable.h
    • [DEFINE_HASHTABLE 定义哈希表](#DEFINE_HASHTABLE 定义哈希表)
    • [hlist_for_each_entry 遍历哈希表](#hlist_for_each_entry 遍历哈希表)
    • [hash_add 将一个对象添加到哈希表](#hash_add 将一个对象添加到哈希表)

include/linux/hashtable.h

DEFINE_HASHTABLE 定义哈希表

c 复制代码
#define DEFINE_HASHTABLE(name, bits)						\
	struct hlist_head name[1 << (bits)] =					\
			{ [0 ... ((1 << (bits)) - 1)] = HLIST_HEAD_INIT }

hlist_for_each_entry 遍历哈希表

c 复制代码
#define hlist_entry(ptr, type, member) container_of(ptr,type,member)

#define hlist_for_each(pos, head) \
	for (pos = (head)->first; pos ; pos = pos->next)

#define hlist_for_each_safe(pos, n, head) \
	for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \
	     pos = n)

#define hlist_entry_safe(ptr, type, member) \
	({ typeof(ptr) ____ptr = (ptr); \
	   ____ptr ? hlist_entry(____ptr, type, member) : NULL; \
	})

/**
 * hlist_for_each_entry - 遍历给定类型的列表
 * @pos:	用作循环游标的类型 *。
 * @head:	您列表的开头。
 * @member:	结构体内 hlist_node 的名称。
 */
#define hlist_for_each_entry(pos, head, member)				\
	for (pos = hlist_entry_safe((head)->first, typeof(*(pos)), member);\
	     pos;							\
	     pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))


/**
 * hash_for_each_possible - 遍历所有可能哈希到同一桶的对象 
 * @name: 要遍历的哈希表 * @obj: 用作每个条目的循环游标的类型* 
 * @member: 结构体内 hlist_node 的名称 
 * @key: 要遍历的对象的键
 */
#define hash_for_each_possible(name, obj, member, key)			\
	hlist_for_each_entry(obj, &name[hash_min(key, HASH_BITS(name))], member)

hash_add 将一个对象添加到哈希表

c 复制代码
/**
 * hlist_add_head - add a new entry at the beginning of the hlist
 * @n: new entry to be added
 * @h: hlist head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
{
	struct hlist_node *first = h->first;
	WRITE_ONCE(n->next, first);
	if (first)
		WRITE_ONCE(first->pprev, &n->next);
	WRITE_ONCE(h->first, n);
	WRITE_ONCE(n->pprev, &h->first);
}

/**
 * hash_add - 将一个对象添加到哈希表 
 * @hashtable: 要添加到的哈希表 
 * @node: 要添加的对象的 &struct hlist_node 
 * @key: 要添加的对象的键
 */
#define hash_add(hashtable, node, key)						\
	hlist_add_head(node, &hashtable[hash_min(key, HASH_BITS(hashtable))])
相关推荐
SudosuBash1 小时前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI12 小时前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行1 天前
Linux和window共享文件夹
linux
木心月转码ing1 天前
WSL+Cpp开发环境配置
linux
崔小汤呀3 天前
最全的docker安装笔记,包含CentOS和Ubuntu
linux·后端
何中应3 天前
vi编辑器使用
linux·后端·操作系统
何中应3 天前
Linux进程无法被kill
linux·后端·操作系统
何中应3 天前
rm-rf /命令操作介绍
linux·后端·操作系统
何中应3 天前
Linux常用命令
linux·操作系统
葛立国3 天前
从 / 和 /dev 说起:Linux 文件系统与挂载点一文理清
linux