Home > Article > Backend Development > Nginx advanced data structure source code analysis (2) ----- dynamic array
ngx_array_t is a sequential container, which is widely used in Nginx. It stores elements in the form of an array and supports dynamically changing the size of the array when the upper limit of the array capacity is reached. It is similar to the vector container in C++, and has a built-in memory pool encapsulated by Nginx. Therefore, the memory it allocates is also applied for in the memory pool.
ngx_array_t has the following three advantages;
(1) Fast access;
(2) Allows uncertainty in the number of elements;
(3) Responsible The allocation of memory occupied by elements will be managed uniformly by the memory pool.
There are two ways to expand the capacity of dynamic arrays:
(1) If the remaining space in the current memory pool is greater than or equal to the space that needs to be added this time, then this expansion will only expand the new space. Space.
(2) If the remaining space in the current memory pool is less than the space that needs to be added this time, then for the ngx_array_push method, the capacity of the original dynamic array will be doubled, and for ngx_array_push_n, The amount of expansion is determined based on the parameters and the capacity of the original dynamic array.
done out out out out out of Destroy the dynamic array:
typedef struct {
void *elts;//首地址
ngx_uint_t nelts;//已使用的元素个数
size_t size;//每个数组元素占用的内存大小
ngx_uint_t nalloc;//可以容纳元素的个数的总大小
ngx_pool_t *pool;//内存池对象
} ngx_array_t;
static ngx_inline ngx_int_t ngx_array_init(ngx_array_t *array, ngx_pool_t *pool, ngx_uint_t n, size_t size)//初始化数组 { /* * set "array->nelts" before "array->elts", otherwise MSVC thinks * that "array->nelts" may be used without having been initialized */ array->nelts = 0; //首地址为0 array->size = size; //每个元素所占内存大小 array->nalloc = n; //分配的元素个数 array->pool = pool; //内存池对象 //申请n*size这么大的内存空间 array->elts = ngx_palloc(pool, n * size); if (array->elts == NULL) { return NGX_ERROR; } return NGX_OK; }
Add n elements to the current dynamic array:
ngx_array_t *
ngx_array_create(ngx_pool_t *p, ngx_uint_t n, size_t size)//创建数组
{
ngx_array_t *a;
a = ngx_palloc(p, sizeof(ngx_array_t));//申请数组本身的内存
if (a == NULL) {
return NULL;
}
if (ngx_array_init(a, p, n, size) != NGX_OK) {//初始化,即申请可以存储元素的内存
return NULL;
}
return a;
}
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
The above introduces the Nginx advanced data structure source code analysis (2) ----- dynamic array, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.