说说你见过哪些拍案叫绝的C代码?
说说你见过哪些拍案叫绝的C代码,大佬们一起来聊聊。我先说两个kenrel的秀儿
1. container_of 的实现
这个由元素到结构体的宏真的秀:((type *)0
程序代码:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
2. wake up events 计数
一个32位数据分上半部16位和下半部16位,用原子操作同时更新
程序代码:
53 static void split_counters(unsigned int *cnt, unsigned int *inpr)
54 {
55 unsigned int comb = atomic_read(&combined_event_count);
56
57 *cnt = (comb >> IN_PROGRESS_BITS); //处理完成的
58 *inpr = comb & MAX_IN_PROGRESS; // 正在处理的
59 }
if active
547 cec = atomic_inc_return(&combined_event_count);
if deactive
677 cec = atomic_add_return(MAX_IN_PROGRESS, &combined_event_count);









