#ifndef MRT_COLLECTOR_RESOURCES_H
#define MRT_COLLECTOR_RESOURCES_H
#include "Base/Macros.h"
#include "FinalizerProcessor.h"
#include "Heap/Collector/TaskQueue.h"
#include "Heap/GcThreadPool.h"
#include "Inspector/CjHeapData.h"
#include "TaskQueue.h"
namespace MapleRuntime {
class CollectorProxy;
class CollectorResources {
public:
MRT_EXPORT static void* GCMainThreadEntry(void* arg);
explicit CollectorResources(CollectorProxy& proxy) : collectorProxy(proxy) {}
ATTR_NO_INLINE virtual ~CollectorResources() = default;
void Init();
void Fini();
void StopGCWork();
void RequestGC(GCReason reason, bool async);
void WaitForGCFinish();
void RunTaskLoop();
void NotifyGCFinished(uint64_t gcIndex);
int32_t GetGCThreadCount(const bool isConcurrent) const;
GCThreadPool* GetThreadPool() const { return gcThreadPool; }
bool IsHeapMarked() const { return isHeapMarked; }
void SetHeapMarked(bool value) { isHeapMarked = value; }
bool IsGcStarted() const { return isGcStarted.load(std::memory_order_relaxed); }
void SetGcStarted(bool val) { isGcStarted.store(val, std::memory_order_relaxed); }
bool IsGCActive() const { return Heap::GetHeap().IsGCEnabled() && isGCActive.load(std::memory_order_relaxed); }
FinalizerProcessor& GetFinalizerProcessor() { return finalizerProcessor; }
void BroadcastGCCompletion();
GCStats& GetGCStats() { return gcStats; }
void RequestHeapDump(GCTask::TaskType gcTask);
private:
void StartGCThreads();
void TerminateGCTask();
void StopGCThreads();
void RequestAsyncGC(GCReason reason);
void RequestGCAndWait(GCReason reason);
void PostIgnoredGcRequest(GCReason reason);
GCThreadPool* gcThreadPool = nullptr;
int32_t gcThreadCount = 1;
TaskQueue<GCExecutor>* taskQueue = nullptr;
pthread_t gcMainThread = 0;
std::atomic<pid_t> gcTid{ 0 };
std::atomic<bool> gcThreadRunning = { false };
std::atomic<uint64_t> finishedGcIndex = { 0 };
std::mutex gcFinishedCondMutex;
std::condition_variable gcFinishedCondVar;
std::atomic<bool> isGcStarted = { false };
std::atomic<bool> isGCActive = { true };
bool isHeapMarked = false;
std::atomic<int> criticalNum{ 0 };
int gcWorking = 0;
#if defined(_WIN64) || defined(__APPLE__)
std::condition_variable gcWorkingCV;
std::mutex gcWorkingMtx;
__attribute__((always_inline)) inline void WaitUntilGCDone()
{
std::unique_lock<std::mutex> gcWorkingLck(gcWorkingMtx);
gcWorkingCV.wait(gcWorkingLck);
}
__attribute__((always_inline)) inline void WakeWhenGCDone()
{
std::unique_lock<std::mutex> gcWorkingLck(gcWorkingMtx);
gcWorkingCV.notify_all();
}
#endif
CollectorProxy& collectorProxy;
FinalizerProcessor finalizerProcessor;
GCStats gcStats;
};
}
#endif