1 传统的分配与释放内存的函数缺点:
void *malloc(size_t size);
void *calloc(size_t nmemb,size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
缺点1:
高并发时较小内存块使用导致系统调用频繁,降低了系统的执行效率
缺点2:
频繁使用时增加了系统内存的碎片,降低内存使用效率
缺点3:
没有垃圾回收机制,容易造成内存泄漏,导致内存枯竭
缺点4:
内存分配与释放的逻辑在程序中相隔较远时,降低程序的稳定性
2 内存池概述
在使用内存之前,先申请分配一定数量的、大小相等(一般情况下)的内存块留作备用。当有新的内存需求时,就从内存池中分出一部分内存块,若内存块不够再继续申请新的内存,统一对程序所使用的内存进行统一的分配和回收。这样做的一个显著优点是,使得内存分配效率得到很大的提升。
3 内存池架构图
4 内存池内存操作API
5 内存池源码剖析
5-1头文件
mem_core.h
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#ifndef _NGX_CORE_H_INCLUDED_
#define _NGX_CORE_H_INCLUDED_
#define NGX_HAVE_POSIX_MEMALIGN 1
typedef struct ngx_pool_s ngx_pool_t;
#define NGX_OK 0
#define NGX_ERROR -1
#define NGX_AGAIN -2
#define NGX_BUSY -3
#define NGX_DONE -4
#define NGX_DECLINED -5
#define NGX_ABORT -6
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <sys/stat.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
typedef intptr_t ngx_int_t;
typedef uintptr_t ngx_uint_t;
#define NGX_ALIGNMENT sizeof(unsigned long) /* platform word */
#define ngx_align(d, a) (((d) + (a - 1)) & ~(a - 1))
#define ngx_align_ptr(p, a) \
(u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))
#define ngx_memzero(buf, n) (void) memset(buf, 0, n)
#include "mem_alloc.h"
#include "mem_pool_palloc.h"
mem_alloc.h
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#ifndef _NGX_ALLOC_H_INCLUDED_
#define _NGX_ALLOC_H_INCLUDED_
#include "mem_core.h"
void *ngx_alloc(size_t size);
void *ngx_calloc(size_t size);
#define ngx_free free
/*
* Linux has memalign() or posix_memalign()
* Solaris has memalign()
* FreeBSD 7.0 has posix_memalign(), besides, early version's malloc()
* aligns allocations bigger than page size at the page boundary
*/
/*#if (NGX_HAVE_POSIX_MEMALIGN || NGX_HAVE_MEMALIGN)
void *ngx_memalign(size_t alignment, size_t size);
#else
*/
#define ngx_memalign(alignment, size) ngx_alloc(size)
/*
#endif
*/
extern ngx_uint_t ngx_pagesize;
extern ngx_uint_t ngx_pagesize_shift;
extern ngx_uint_t ngx_cacheline_size;
#endif /* _NGX_ALLOC_H_INCLUDED_ */
mem_pool_palloc.h
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#ifndef _NGX_PALLOC_H_INCLUDED_
#define _NGX_PALLOC_H_INCLUDED_
#include "mem_core.h"
/*
* NGX_MAX_ALLOC_FROM_POOL should be (ngx_pagesize - 1), i.e. 4095 on x86.
* On Windows NT it decreases a number of locked pages in a kernel.
*/
#define NGX_MAX_ALLOC_FROM_POOL (ngx_pagesize - 1)
#define