您当前的位置: 首页 >  linux

qianbo_insist

暂无认证

  • 0浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

linux kernel 下的hash 和链表 应用

qianbo_insist 发布时间:2021-02-15 13:22:44 ,浏览量:0

记得很久以前,写linux 内核模块的时候,使用linux内核态下的hash表,非常简单好用,这个也可以用在用户态,linux上或者windows上都可以使用。

1、定义一个节点node
#include "hlist.h"
typedef struct node {  
	unsigned char ch;
	int  this_data;

	struct list_head  i_list;
	struct hlist_node i_hash;

	char str_data[32];
	int end_data;
} *pnode;
2、加入hash的size

#define HASHSIZE 0xff 这里可以自己修改大小的

2.1 定义hash算法函数

这个函数定义的比较简单,简单使用整形,不超过hash表的大小

unsigned int gethash(int c)  
{  
    return (c & HASHSIZE);  
} 
2.2 如果key为字符串,也可以使用字符算hash函数
	//加法hash,需要平均分配到各个线程中
	static int hash_add(const char* key, int prime)
	{

		int hash, i;
		int len = strlen(key);
		for (hash = len, i = 0; i this_data = value;
	sprintf(p->str_data, "data:%d", value);
	int hash = gethash(value);
	if (hash i_hash, &hlist[hash]);
		return 0;
	}
	return -1;
}
//搜索函数
struct node * node_search(int value)
{
	struct hlist_node *hp;
	int hash = gethash(value);
	hlist_for_each(hp, &hlist[hash]) {
		struct node *p = hlist_entry(hp, struct node, i_hash);
		if (value == p->this_data)
		{
			return p;
		}
	}
	return NULL;
}
//删除函数
int node_delete(int value)
{
	int hash,num = 0;
	struct hlist_node *hp;
	struct hlist_node *hn;
	hash = gethash(value);
	hlist_for_each_safe(hp, hn, &hlist[hash]) {
		struct node *p = hlist_entry(hp, struct node, i_hash);
		printf("hlist_del: %s\n", p->str_data);
		if(value == p->this_data)
		hlist_del(hp);
		++num;
	}
	return num;
}
//清空所有
int node_delete_all()
{
	struct hlist_node *hp;
	struct hlist_node *hn;
	for (int i = 0; i             
关注
打赏
1663161521
查看更多评论
0.0382s