内存分配时考虑了小块和大块,用不同函数实现,
如果申请的空间大小 <= 当前内存池的max,调用ngx_palloc_small();
否则调用 ngx_palloc_large()
void *ngx_palloc(ngx_pool_t *pool, size_t size)
{
#if !(NGX_DEBUG_PALLOC)
if (size <= pool->max) {
return ngx_palloc_small(pool, size, 1);
}
#endif
return ngx_palloc_large(pool, size);
}
void *ngx_pnalloc(ngx_pool_t *pool, size_t size)
{
#if !(NGX_DEBUG_PALLOC)
if (size <= pool->max) {
return ngx_palloc_small(pool, size, 0);
}
#endif
return ngx_palloc_large(pool, size);
}
在ngx_pcalloc()函数中,依然是调用 ngx_palloc(),但会将申请的空间全部置为0.
void *ngx_pcalloc(ngx_pool_t *pool, size_t size)
{
void *p;
p = ngx_palloc(pool, size);
if (p) {
ngx_memzero(p, size);
}
return p;
}
static ngx_inline void *
ngx_palloc_small(ngx_pool_t *pool, size_t size, ngx_uint_t align)
{
u_char *m;
ngx_pool_t *p;
p = pool->current; // 1
do {
m = p->d.last; // 2
if (align) { // 3
m = ngx_align_ptr(m, NGX_ALIGNMENT);
}
if ((size_t) (p->d.end - m) >= size) { // 4
p->d.last = m + size;
return m;
}
p = p->d.next; // 5
} while (p);
return ngx_palloc_block(pool, size);
}
static void *
ngx_palloc_block(ngx_pool_t *pool, size_t size)
{
u_char *m;
size_t psize;
ngx_pool_t *p, *new;
psize = (size_t) (pool->d.end - (u_char *) pool); // 6
m = ngx_memalign(NGX_POOL_ALIGNMENT, psize, pool->log); // 7
if (m == NULL) {
return NULL;
}
new = (ngx_pool_t *) m; // 8
new->d.end = m + psize; // 9
new->d.next = NULL;
new->d.failed = 0;
m += sizeof(ngx_pool_data_t); // 10
m = ngx_align_ptr(m, NGX_ALIGNMENT); // 11
new->d.last = m + size; // 12
// 13
for (p = pool->current; p->d.next; p = p->d.next) {
if (p->d.failed++ > 4) {
pool->current = p->d.next;
}
}
p->d.next = new; // 14
return m;
}
#define ngx_align_ptr(p, a) \
(u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))