EHS/src/GarbageCollector.cpp

134 lines
2.0 KiB
C++
Raw Normal View History

2024-01-31 22:28:19 -08:00
#include "ehs/GarbageCollector.h"
namespace ehs
{
UInt_32 GarbageCollectionThread(void* params)
{
while (GarbageCollector::IsRunning())
{
GarbageCollector::Poll();
Thread::SleepFor(50);
}
GarbageCollector::Dump();
return 0;
}
Vector<BaseObj*> GarbageCollector::garbage(0, 1000);
UInt_64 GarbageCollector::max = 10;
Thread GarbageCollector::thread;
Mutex GarbageCollector::mutex;
bool GarbageCollector::running = false;
bool GarbageCollector::Has(const BaseObj* obj)
{
for (UInt_64 i = 0; i < garbage.Size(); ++i)
if (garbage[i] == obj)
return true;
return false;
}
void GarbageCollector::Start()
{
if (running)
return;
mutex.Initialize();
thread.Start(GarbageCollectionThread, nullptr);
running = true;
}
void GarbageCollector::Stop()
{
if (!running)
return;
running = false;
thread.Join();
}
void GarbageCollector::Add(BaseObj* obj)
{
if (!obj)
return;
/*
if (Has(obj))
{
EHS_LOG_INT("Warning", 1, obj->GetTypeId() + " object with address of, \"" + Str_8::FromNum<USize>((USize)obj) + "\" is already in garbage.");
return;
}
*/
garbage.Push(obj);
}
void GarbageCollector::SetMax(const UInt_64 newMax)
{
max = newMax;
}
UInt_64 GarbageCollector::GetMax()
{
return max;
}
void GarbageCollector::SetStride(const UInt_64 newStride)
{
Dump();
garbage = Vector<BaseObj*>(0, newStride);
}
UInt_64 GarbageCollector::GetStride()
{
return garbage.Stride();
}
UInt_64 GarbageCollector::Size()
{
return garbage.Size();
}
void GarbageCollector::Poll()
{
if (running)
mutex.Lock();
UInt_64 i = 0;
while (i < garbage.Size())
{
garbage.Swap(i, garbage.End());
delete garbage.Pop();
}
if (running)
mutex.Unlock();
}
void GarbageCollector::Dump()
{
if (running)
mutex.Lock();
for (UInt_64 i = 0; i < garbage.Size(); ++i)
delete garbage[i];
garbage.Clear();
if (running)
mutex.Unlock();
}
bool GarbageCollector::IsRunning()
{
return running;
}
}