23

ngx_align 值对齐宏

 3 years ago
source link: http://www.cnblogs.com/shuqin/p/13832722.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ngx_align 值对齐宏

ngx_align 为nginx中的一个值对齐宏。主要在需要内存申请的地方使用,为了减少在不同的 cache line 中内存而生。

// d 为需要对齐的
// a 为对齐宽度,必须为 2 的幂
// 返回对齐值
#define ngx_align(d, a)     (((d) + (a - 1)) & ~(a - 1))

原理简单,利用 ~(a - 1) 的低位全为 0。在与 ~(a - 1)& 操作时,低位的1被丢弃,就得到了a倍数的值(对齐)。

如果使用原始值直接与 ~(a - 1)& 操作,那么得到的对齐值是会小于等于原始值的,这样会造成内存重叠,而期望的对齐值是一个大于等于原始值的,所以需要加上一个数来补上至对齐值这中间的差,这个数为 (a - 1) ,选择这个数的原因是 (a - 1) & ~(a - 1) 的结果为0:

mIJvAvF.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK