[英]When do we need to use posix_memalign instead of malloc?
Seems posix_memalign
let you choose a customized alignment
,but when is that necessary? 似乎
posix_memalign
让您选择自定义alignment
,但什么时候需要?
malloc
has already done the alignment work internally. malloc
已经在内部完成了对齐工作。
UPDATE UPDATE
The exact reason I ask this is because I see nginx does this, ngx_memalign(NGX_POOL_ALIGNMENT, size, log);
我问这个的确切原因是因为我看到nginx这样做,
ngx_memalign(NGX_POOL_ALIGNMENT, size, log);
,here NGX_POOL_ALIGNMENT
is defined as 16
, nginxs.googlecode.com/svn-history/trunk/src/core/ngx_palloc.c ,这里
NGX_POOL_ALIGNMENT
被定义为16
, nginxs.googlecode.com/svn-history/trunk/src/core/ngx_palloc.c
Basically, if you need tougher alignment than malloc will give you. 基本上,如果你需要比malloc更强的对齐方式给你。 Malloc generally returns a pointer aligned such, that it may be used with any of the primitive types (often, 8 bytes on common desktop machines).
Malloc通常返回一个对齐的指针,它可以与任何基本类型一起使用(通常,在普通台式机上使用8个字节)。
However, sometimes you need memory aligned on other boundaries, for example 4K-aligned, etc. In this case, you would need memalign
. 但是,有时您需要在其他边界上对齐内存,例如4K对齐等。在这种情况下,您需要
memalign
。
You would need this, for example, 你需要这个,例如,
The only benefits of posix_memalign
, as far as I can tell, are: 据我所知,
posix_memalign
的唯一好处是:
N
bits of a pointer zero so you can store an N
-bit integer in the low bits. N
位保持为零,这样你就可以在低位存储一个N
位整数。 :-) Various hardware may have alignment requirements which malloc
cannot satisfy. 各种硬件可能具有
malloc
无法满足的对齐要求。 The Linux man page gives one such example, I quote: Linux手册页给出了一个这样的例子,我引述:
On many systems there are alignment restrictions, eg on buffers used for direct block device I/O.
在许多系统上存在对齐限制,例如,用于直接块设备I / O的缓冲区。 POSIX specifies the pathconf(path,_PC_REC_XFER_ALIGN) call that tells what alignment is needed.
POSIX指定pathconf(path,_PC_REC_XFER_ALIGN)调用,该调用指示需要什么对齐。
A couple of uses: 一些用途:
Some processors have instructions that will only work on data that is aligned on a power of two greater than or equal to the buffer size - for example bit reverse addressing instructions used in ffts (fast fourier transforms). 某些处理器的指令仅适用于大于或等于缓冲区大小的2的幂对齐的数据 - 例如ffts中使用的位反向寻址指令(快速傅里叶变换)。
To align data to cache boundaries to optimize access in multiprocessing applications so that data in the same cache line isn't being accessed by two processors simultaneously. 将数据与高速缓存边界对齐以优化多处理应用程序中的访问,以便两个处理器不会同时访问同一高速缓存行中的数据。
Basically, if you don't need to do absurd levels of optimizations and/or your hardware doesn't demand that an array be on a particular boundary then you can forget about posix_memalign. 基本上,如果您不需要进行荒谬的优化级别和/或您的硬件不要求阵列在特定边界上,那么您可以忘记posix_memalign。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.