内存池操作实例【5.5.1节,例5-3】

代码 【mempool.c】

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mempool.h>

#define MIN_ELEMENT 4
#define TEST_ELEMENT 4

typedef struct 
{
	int number;
	char string[128];
}TMemElement;

int elementcount = 0;

void *mempool_alloc_test(int gfp_mask, void *pool_data)
{
	TMemElement *data;
	printk("------> mempool_alloc_test \n");

	data = kmalloc(sizeof(TMemElement), gfp_mask);

	if(data != NULL)
	{
		data->number = elementcount++;
	}
	return data;
}

void mempool_free_test(void *element, void *pool_data)
{
	printk("------> call mempool_free_test \n");
	if(element != NULL) 
	{
		kfree(element);
	}	
}

int mempool_init(void)
{
	mempool_t *mp;
	TMemElement *element[TEST_ELEMENT];
	int lp;

	printk("Module MEMPOOL Test \n");

	memset(element, 0, sizeof(element));

	printk("mempool allocate \n");

	mp = mempool_create(MIN_ELEMENT, mempool_alloc_test, mempool_free_test, NULL);
	
	printk("mempool allocate \n");

	for(lp=0; lp < TEST_ELEMENT; lp++)

	{
		element[lp] = mempool_alloc(mp, GFP_KERNEL);
		if(element[lp] == NULL)
		{
			printk("allocate fail \n");
		}
		else 
		{
			sprintf(element[lp]->string, "alloc data %d \n", element[lp]->number);
			printk(element[lp]->string);
		}
		
	}

	printk("mempool free \n");

	for(lp=0; lp < TEST_ELEMENT; lp++)
	{
		if(element[lp] != NULL)
		{
			mempool_free(element[lp], mp);
		}
	}
	printk("call mempool_destroy \n");
	mempool_destroy(mp);

	return 0;
}

void mempool_exit(void)
{
	printk("Module MEMPOOL Test End \n");
	
}

module_init(mempool_init);
module_exit(mempool_exit);

MODULE_LICENSE("Dual BSD/GPL");


运行结果:

root@xiangpingli:/home/linux/study/5.5.1# insmod mempool.ko
root@xiangpingli:/home/linux/study/5.5.1# dmesg
[ 6912.339254] Module MEMPOOL Test
[ 6912.339256] mempool allocate
[ 6912.339257] ------> mempool_alloc_test
[ 6912.339258] ------> mempool_alloc_test
[ 6912.339259] ------> mempool_alloc_test
[ 6912.339259] ------> mempool_alloc_test
[ 6912.339260] mempool allocate
[ 6912.339260] ------> mempool_alloc_test
[ 6912.339262] alloc data 4
[ 6912.339262] ------> mempool_alloc_test
[ 6912.339263] alloc data 5
[ 6912.339264] ------> mempool_alloc_test
[ 6912.339264] alloc data 6
[ 6912.339265] ------> mempool_alloc_test
[ 6912.339265] alloc data 7
[ 6912.339266] mempool free
[ 6912.339266] ------> call mempool_free_test
[ 6912.339267] ------> call mempool_free_test
[ 6912.339268] ------> call mempool_free_test
[ 6912.339268] ------> call mempool_free_test
[ 6912.339269] call mempool_destroy
[ 6912.339270] ------> call mempool_free_test
[ 6912.339270] ------> call mempool_free_test
[ 6912.339271] ------> call mempool_free_test
[ 6912.339272] ------> call mempool_free_test
root@xiangpingli:/home/linux/study/5.5.1#

 

 

 

你可能感兴趣的:(struct,String,Module,null)