ACE 中 ACE_Allocator 使用例子

ACE_Cached_Allocator
该分配器预先分配内存池,其中含有特定数目和大小的内存chunk。这些chunk在内部空闲表(free list)中进行维护,并在收到内存请求(malloc())时被返回。当应用调用free()时,chunk被归还到内部空闲表、而不是OS中。

 

// Memapply.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include "ace/Containers.h"
#include "ace/Malloc_T.h"
#include "ace/Synch.h" 

class book
{
	book(int code, char* name)
	{
		code_ = code;
		strcpy_s(name_, 20, name);
	}
	virtual ~book();
private:
	int  code_;
	char name_[20];
public:
	void setbook(int code, char* name)
	{
		code_ = code;
		strcpy_s(name_, 20, name);
	}
	void output()
	{
		printf("code=%d name=%s\n", code_, name_);
	}
};


int ACE_TMAIN(int argc, ACE_TCHAR* agrv[])
{
	
	ACE_Allocator *allocator = 0;

	size_t block_size = sizeof(ACE_Node<book>);
	ACE_NEW_RETURN(allocator,  ACE_Dynamic_Cached_Allocator<ACE_Null_Mutex>(10, block_size), -1);

	book* pbook[20];
	for(int i = 0; i < 20; i++)
	{
		pbook[i] = NULL;
	}

	for(int i = 0; i < 20; i++)
	{
		pbook[i] = (book*)allocator->malloc(sizeof(ACE_Node<book>));
		if (pbook[i] != 0)
		{
			char bookname[50];
			sprintf_s(bookname, 50,"wangxu_%02d", i);
			pbook[i]->setbook(i, bookname);
			pbook[i]->output();
		}
		else
		{	
			printf("%d apply for memeory error\n", i);
		}
	}
 
	printf("free 1 block\n");
	allocator->free(pbook[0]);

	printf("apply for again\n");
	pbook[0] = (book*)allocator->malloc(sizeof(ACE_Node<book>));
	pbook[0]->setbook(99, "zhangsan");
	pbook[0]->output();

	delete allocator;

	getchar();
	return 0;
}


 


你可能感兴趣的:(ACE 中 ACE_Allocator 使用例子)