C 语言实现的内存池 mpool.c : 适用于Windows和Linux
cheungmine
当程序频繁分配内存,或者管理很多大块内存的时候,我们就需要一个简洁高效的内存池(memory pool)。很多语言提供了这个基础设施,这里我提供一个C语言的版本mpool.c:原始的mpool仅仅提供Unix/Linux的版本,我增加了Windows的版本,这样这个mpool就成为适用于Windows和Linux的完整的版本了。
全部的mpool有5个文件:mpool.h
mpool_loc.h
mix4win.h (这个文件是我增加的)
mpool.c
Makefile
有2个测试文件:mpool_t.c (自带的Linux上的测试文件)
main.c (我写的Windows上的测试文件)
如果你觉得本文对你有帮助,请点击下面的链接,以获得关于我的信息:
http://blog.csdn.net/cheungmine/article/details/8258551
本文全部内容可以在下面的链接下载到:
http://download.csdn.net/detail/cheungmine/4859693
/** * test mpool on windows * * cheungmine * 12/7/2012 */#include <stdlib.h> #include <stdio.h>#include <assert.h>#include "../mpool.h"#define NUM_BLKS 10000#define MAX_MEM_SIZE (1024*1024*128)int main(){ int i, ret; unsigned int flags = 0, pool_page_size; unsigned long num_alloced, user_alloced, max_alloced, tot_alloced; mpool_t *pool; void *blks[NUM_BLKS+1]; int blk_size; int page_size = 0; /* open our memory pool */ pool = mpool_open(MPOOL_FLAG_BEST_FIT, page_size, NULL, &ret); if (pool == NULL) { (void)fprintf(stderr, "Error in mpool_open: %s\n", mpool_strerror(ret)); exit(1); } for (i=1; i<NUM_BLKS; i++) { blk_size = (1024*i)%MAX_MEM_SIZE; blks[i] = mpool_calloc(pool, blk_size, sizeof(char), &ret); } /* free all blks */ mpool_clear(pool); for (i=100; i<NUM_BLKS; i++) { blk_size = (1024*i)%MAX_MEM_SIZE; blks[i] = mpool_calloc(pool, blk_size, sizeof(char), &ret); } /* free blks */ for (i=100; i<NUM_BLKS; i++) { blk_size = (1024*i)%MAX_MEM_SIZE; mpool_free(pool, blks[i], blk_size); } /* get stats from the pool */ ret = mpool_stats(pool, &pool_page_size, &num_alloced, &user_alloced, &max_alloced, &tot_alloced); if (ret == MPOOL_SUCCESS) { (void)printf("Pool page size = %d. Number active allocated = %lu\n", pool_page_size, num_alloced); (void)printf("User bytes allocated = %lu. Max space allocated = %lu\n", user_alloced, max_alloced); (void)printf("Total space allocated = %lu\n", tot_alloced); } else { (void)fprintf(stderr, "Error in mpool_stats: %s\n", mpool_strerror(ret)); } /* free all blks, it is not necessary to clear before close pool */ ret = mpool_clear(pool); assert(ret == MPOOL_SUCCESS); /* close the pool */ ret = mpool_close(pool); if (ret != MPOOL_SUCCESS) { (void)fprintf(stderr, "Error in mpool_close: %s\n", mpool_strerror(ret)); exit(1); } exit(0);}
http://download.csdn.net/detail/cheungmine/4859693