nn::nlib::CachedHeap
, nn::nlib::CentralHeap
を明示的に利用してメモリの確保と解放を行います。
nmalloc/nfree
を利用した場合、間接的にこれらのクラスを利用することになりますが、明示的に利用することも可能です。 このサンプルはその利用方法を説明しています。
nmalloc経由で利用するのではなく明示的に利用することにより、プロセス全体でCentralHeap
を共有するのではなく、モジュール別にCentralHeap
を複数利用したり、単一スレッド内でCachedHeap
を複数利用したりすることが可能になります。
using nlib_ns::threading::Thread;
using nlib_ns::heap::CentralHeap;
using nlib_ns::heap::CachedHeap;
const size_t heapmem_size = 1024 * 512;
CentralHeap g_centralheap;
class HeapSetup {
public:
HeapSetup() {
g_centralheap.Init(&heapmem[0], heapmem_size, 0);
}
~HeapSetup() {
g_centralheap.Finalize();
}
};
volatile bool g_success = true;
static void ThreadFunc(void* ptr) {
NLIB_UNUSED(ptr);
CachedHeap heap;
g_success = false;
return;
}
const int n = 1000;
void* p[n];
for (int j = 0; j < 1000; ++j) {
for (int i = 0; i < n; ++i) {
p[i] = heap.Alloc(8);
if (!p[i]) g_success = false;
}
for (int i = 0; i < n; ++i) {
heap.Free(p[i]);
}
}
}
const int kNumThread = 10;
Thread th[kNumThread];
static bool SampleMain(int, char**) {
HeapSetup obj;
{
uint64_t from, to;
for (int i = 0; i < kNumThread; ++i) {
th[i].StartRaw(ThreadFunc, NULL);
}
for (int i = 0; i < kNumThread; ++i) {
th[i].Join();
}
nlib_printf(
"Small: using CachedHeap: %" PRIu64
" msec\n", to - from);
}
return g_success;
}
NLIB_MAINFUNC