开始前先大概看下内存池整体结构:
下面本文从demo出发,大致debug看下创建和使用流程。
#include <stdio.h>
#include <string.h>
#include "nginx.h"
#include "ngx_hash.h"
#include "ngx_string.h"
#include "ngx_config.h"
#include "ngx_conf_file.h"
#include "ngx_core.h"
#include "ngx_palloc.h"
#define POOL_SIZE 2000
typedef struct Test_2
{
int a ;
int b ;
} test2;
void testPalloc(){
//1、内存池创建
ngx_pool_t * pool = ngx_create_pool(POOL_SIZE,NULL);
//2、结构体内存申请
void *mem1 = ngx_palloc(pool, sizeof(test2));
void *mem2 = ngx_palloc(pool,sizeof(test2));
void *mem3 = ngx_palloc(pool,1918);
test2 *test;
test = mem1;
test->a = 15;
test->b = 32;
//3、大内存申请
void *mem4 = ngx_palloc(pool, 5000);
void *mem5 = ngx_palloc(pool, 5000);
//4、内存释放
ngx_destroy_pool(pool);
}
void main(){
testPalloc();
}
1、内存池创建
2、结构体内存申请
当d.last到d.end的空间足够
当mem2申请内存时,流程一样,然后mem2指向d.last 即0x960068,然后d.last再后移8个字节到达0x960070。
当mem3申请时,申请的空间为1918,小于max:1920,但当前的pool的剩余空间肯定是不够1918的,因此要进入pool扩容(以链表形式)
当为啥要fail>4后,移动当前pool的current指向?即以前的大概率已经完成分配了,即便没有分配的也不再分配,保证current之后遍历的节点不要过长,提高分配效率。
3、大内存申请
men4与men5申请长度5000的内存,超过max 1920的限制,将执行大内存申请的逻辑
4、内存释放
NGINX的内存池是NGINX其他数据结构的基础,创建其他数据结构的实例基本都需要通过内存池分配空间