目录
双向循环链表list_head
什么是双向循环链表就不说了,学习linux的应该都有C家族的基础。
struct list_head {
struct list_head *next, *prev;
};
list_head不是拿来单独用的,它一般被嵌到其它结构中,如:
struct str{
char c;
struct list_head node;
};
创建双向循环链表
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
这样创建双向循环链表太厉害了。
list_for_each_entry
代码:
#define list_for_each_entry(pos, head, member)
for (pos = list_entry((head)->next, typeof(*pos), member);
&pos->member != (head);
pos = list_entry(pos->member.next, typeof(*pos), member))
list_for_each_entry函数是用来遍历双向循环链表的,
pos依次为指向每个节点的指针,除了head,因为Linux内核中的双向循环链表的head节点是不实际使用的。
list_entry通过已知的指向member的指针,获得整个结构体的指针。
bsearch二分查找函数
/*
* bsearch - binary search an array of elements
* @key: pointer to item being searched for
* @base: pointer to first element to search
* @num: number of elements
* @size: size of each element
* @cmp: pointer to comparison function
*
* This function does a binary search on the given array. The
* contents of the array should already be in ascending sorted order
* under the provided comparison function.
*
* Note that the key need not have the same type as the elements in
* the array, e.g. key could be a string and the comparison function
* could compare the string with the struct's name field. However, if
* the key and elements in the array are of the same type, you can use
* the same comparison function for both sort() and bsearch().
*/
void *bsearch(const void *key, const void *base, size_t num, size_t size,
int(*cmp)(const void *key, const void *elt))
{
size_t start = 0, end = num;
int result;
while (start < end) {
size_t mid = start + (end - start) / 2;
result = cmp(key, base + mid * size);
if (result < 0)
end = mid;
else if (result > 0)
start = mid + 1;
else
return (void *)base + mid * size;
}
return NULL;
}
EXPORT_SYMBOL(bsearch);
container_of函数和list_entry函数
container_of函数:根据指向type类型结构体中的一个member成员变量的ptr指针,返回type类型结构的指针
代码:
#ifndef container_of
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) * __mptr = (ptr);\
(type *)((char *)__mptr - offsetof(type, member)); })
#endif
list_entry函数:和container_of函数一样
代码:
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
likely()与unlikely()函数
likely() 与 unlikely()是内核中定义的两个宏
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
likely表示一般为1,unlikely表示一般为0,这是用来优化效率的,不影响程序运行结果