AuroraRuntime/Source/Async/AuGroupState.cpp

133 lines
3.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuGroupState.cpp
Date: 2021-11-1
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "Async.hpp"
#include "AuGroupState.hpp"
#include <Source/IO/Loop/LSAsync.hpp>
namespace Aurora::Async
{
bool GroupState::Init()
{
return true;
}
AuSPtr<ThreadState> GroupState::GetThreadByIndex(ThreadId_t uIndex)
{
{
AU_LOCK_GUARD(this->deinitMutex);
if (AuArraySize(this->wpWorkers) > uIndex)
{
if (auto pState = AuTryLockMemoryType(this->wpWorkers[uIndex]))
{
return pState;
}
}
}
AU_LOCK_GUARD(this->workersMutex);
auto itr = this->workers.find(uIndex);
if (itr == this->workers.end())
{
return {};
}
return itr->second;
}
void GroupState::Decommit(ThreadId_t id)
{
{
AU_LOCK_GUARD(this->deinitMutex);
if (AuArraySize(this->wpWorkers) > id)
{
this->wpWorkers[id] = {};
}
}
AU_LOCK_GUARD(this->workersMutex);
for (auto itr = this->workers.begin();
itr != this->workers.end();
)
{
auto &[id2, pWorker] = *itr;
if (id == id2)
{
itr = this->workers.erase(itr);
}
else
{
itr++;
}
}
}
void GroupState::SignalAll()
{
AU_LOCK_GUARD(this->workersMutex);
for (const auto &[id, pWorker] : this->workers)
{
if (!pWorker)
{
continue;
}
pWorker->sync.SetEvent();
}
}
bool GroupState::AddWorker(ThreadId_t id, AuSPtr<ThreadState> pState)
{
AU_LOCK_GUARD(this->workersMutex);
if (AuArraySize(this->wpWorkers) > id)
{
this->wpWorkers[id] = pState;
}
if (!AuTryInsert(this->workers, AuMakePair(id, pState)))
{
this->wpWorkers[id] = {};
return {};
}
return true;
}
AuSPtr<ThreadState> GroupState::CreateWorker(WorkerId_t workerId, bool bCreate)
{
if (auto pThreadState = AuMakeShared<ThreadState>())
{
pThreadState->thread.bOwnsThread = !bCreate;
pThreadState->thread.id = workerId;
pThreadState->parent = this->SharedFromThis();
if (!pThreadState->Init())
{
SysPushErrorNested();
return {};
}
if (!this->AddWorker(workerId.second, pThreadState))
{
SysPushErrorNested();
return {};
}
return pThreadState;
}
else
{
SysPushErrorMemory();
return {};
}
}
}