search
HomeBackend DevelopmentPHP Tutorialnginx dynamic array ngx_array_t

ngx_array_t is a dynamic array designed in nginx, similar to vector in STL. Below we analyze with examples.

1. Example

<span style="font-size:18px;">#include <stdio.h>
#include "ngx_config.h"
#include "ngx_conf_file.h"
#include "nginx.h"
#include "ngx_core.h"
#include "ngx_string.h"
#include "ngx_palloc.h"
#include "ngx_queue.h"
 
volatile ngx_cycle_t  *ngx_cycle;
 
void ngx_log_error_core(ngx_uint_t level,ngx_log_t *log, ngx_err_t err,
           const char *fmt, ...)
{
}
      
void dump_pool(ngx_pool_t* pool) 
{
   while (pool)
    {
       printf("pool = 0x%x\n", pool); 
       printf("  .d\n"); 
       printf("    .last =0x%x\n", pool->d.last); 
       printf("    .end =0x%x\n", pool->d.end); 
       printf("    .next =0x%x\n", pool->d.next); 
       printf("    .failed =%d\n", pool->d.failed); 
       printf("  .max = %d\n",pool->max); 
       printf("  .current =0x%x\n", pool->current); 
       printf("  .chain =0x%x\n", pool->chain); 
       printf("  .large =0x%x\n", pool->large); 
       printf("  .cleanup =0x%x\n", pool->cleanup); 
       printf("  .log =0x%x\n", pool->log); 
       printf("available pool memory = %d\n\n", pool->d.end -pool->d.last);
             
       ngx_pool_large_t*large = pool->large;
       printf("*****large_pool*******\n");
       while(large) {
            printf("%p->",large);
            large= large->next;
       }
       printf("\n\n");
             
       pool = pool->d.next;
   } 
}
 
typedef struct {
       intarray[128]; // 128 * 4 = 512
}TestNode;
 
int main() 
{ 
   ngx_pool_t *pool; 
 
   printf("--------------------------------\n"); 
   printf("create a new pool:\n"); 
   printf("--------------------------------\n"); 
   pool = ngx_create_pool(1024, NULL); 
   dump_pool(pool); 
      
       ngx_array_t*myArray = ngx_array_create(pool, 1, sizeof(TestNode));
       printf("******ngx_array_create**********\n");
   dump_pool(pool);
      
       TestNode*t1 = ngx_array_push(myArray);
       TestNode*t2 = ngx_array_push(myArray);
       printf("******ngx_array_push**********\n");
   dump_pool(pool);
      
       ngx_array_destroy(myArray);// 这里什么也没做
       dump_pool(pool);
   ngx_destroy_pool(pool); 
   return 0; 
}</stdio.h></span>

Operation results:

--------------------------------
create a new pool:
--------------------------------
pool = 0x95ae020
  .d
   .last = 0x95ae048
   .end = 0x95ae420
   .next = 0x0
   .failed = 0
 .max = 984
 .current = 0x95ae020
  .chain= 0x0
 .large = 0x0
 .cleanup = 0x0
 .log = 0x0
available pool memory = 984
 
*****large_pool*******
NULL
******ngx_array_create**********
pool = 0x95ae020
  .d
   .last = 0x95ae25c
   .end = 0x95ae420
   .next = 0x0
   .failed = 0
 .max = 984
 .current = 0x95ae020
 .chain = 0x0
 .large = 0x0
 .cleanup = 0x0
 .log = 0x0
available pool memory = 452
 
*****large_pool*******
NULL
******ngx_array_push**********
pool = 0x95ae020
  .d
   .last = 0x95ae264
   .end = 0x95ae420
   .next = 0x0
    .failed = 0
 .max = 984
 .current = 0x95ae020
 .chain = 0x0
 .large = 0x95ae25c
 .cleanup = 0x0
 .log = 0x0
available pool memory = 444
 
*****large_pool*******
0x95ae25c->NULL
******ngx_array_destroy******
pool = 0x95ae020
  .d
   .last = 0x95ae264
   .end = 0x95ae420
   .next = 0x0
   .failed = 0
 .max = 984
 .current = 0x95ae020
 .chain = 0x0
 .large = 0x95ae25c
 .cleanup = 0x0
 .log = 0x0
available pool memory = 444
 
*****large_pool*******
0x95ae25c->NULL

1. From the changes in available pool memory, we can know that the memory occupied by the ngx_array_t and ngx_pool_large_t structures themselves is allocated on the memory pool. .

It can be proved from the source code:

ngx_array_t *

ngx_array_create(ngx_pool_t*p, ngx_uint_t n, size_t size)

{

a = ngx_palloc(p, sizeof( ngx_array_t);

large = ngx_palloc(pool,sizeof(ngx_pool_large_t));

}

2. If ngx_array_push is expanded, the original occupied memory will not be released. You can refer to the source code of ngx_array_push, which will not be posted here.

3. If the size of the allocated dynamic array exceeds the capacity of a memory pool (in this case, 1024), ngx_palloc_large will be called to allocate a large block of memory.

4. If the memory occupied by the dynamic array is a large block of memory, ngx_array_destroy will not do anything, and this API has not been called in the nginx kernel source code.

For compilation, please refer to the previous article analyzing the ngx_queue_t structure.

2. References:

"In-depth understanding of nginx" Tao Hui

http://blog.csdn.net/livelylittlefish/article/details/6586946

The above introduces the nginx dynamic array ngx_array_t, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment