AuroraRuntime/Source/Threading/Threads/TLSView.cpp

139 lines
2.7 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: TLSView.cpp
Date: 2021-6-12
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2021-06-27 21:25:29 +00:00
#include "TLSView.hpp"
namespace Aurora::Threading::Threads
{
void TLSViewImpl::Remove(AuUInt64 key)
{
2021-09-06 10:58:08 +00:00
AU_LOCK_GUARD(lock_);
2021-06-27 21:25:29 +00:00
auto a = tls_.find(key);
if (a == tls_.end())
{
return;
}
const auto &handler = a->second.second;
if (handler)
{
handler(a->second.first);
}
tls_.erase(a);
}
TLSViewImpl::~TLSViewImpl()
{
for (const auto &itr : tls_)
{
const auto &handler = itr.second.second;
if (handler)
{
handler(itr.second.first);
}
}
tls_.clear();
}
void *TLSViewImpl::GetTLS(AuUInt64 key, AuMach length, bool noAutoCreate)
{
2021-09-06 10:58:08 +00:00
AU_LOCK_GUARD(lock_);
AuPair<void*, TlsCb>*value;
2021-06-27 21:25:29 +00:00
if (!length)
{
return nullptr;
}
2021-09-06 10:58:08 +00:00
if (!AuTryFind(tls_, key, value))
2021-06-27 21:25:29 +00:00
{
if (noAutoCreate)
{
return nullptr;
}
2022-01-20 16:37:22 +00:00
auto buf = AuMemory::ZAlloc<void *>(length);
2021-06-27 21:25:29 +00:00
if (!buf)
{
return nullptr;
}
2022-03-30 14:16:57 +00:00
auto ok = AuTryInsert(tls_, key, AuMakePair(buf, TlsCb {}));
2021-06-27 21:25:29 +00:00
if (!ok)
{
2022-01-20 16:37:22 +00:00
AuMemory::Free(buf);
2021-06-27 21:25:29 +00:00
return nullptr;
}
ConsiderRehash();
return buf;
}
return value->first;
}
void *TLSViewImpl::InitTLS(AuUInt64 key, AuMach length, const TlsCb &init, const TlsCb &deinit)
{
2021-09-06 10:58:08 +00:00
AU_LOCK_GUARD(lock_);
AuPair<void*, TlsCb>*value;
2021-06-27 21:25:29 +00:00
if (!length)
{
return nullptr;
}
2021-09-06 10:58:08 +00:00
if (AuTryFind(tls_, key, value))
2021-06-27 21:25:29 +00:00
{
return value->first;
}
2022-01-20 16:37:22 +00:00
auto buf = AuMemory::ZAlloc<void *>(length);
2021-06-27 21:25:29 +00:00
if (!buf)
{
return nullptr;
}
TlsCb deinitcb = deinit;
2022-03-30 14:16:57 +00:00
auto ok = AuTryInsert(tls_, key, AuMakePair(buf, deinitcb));
2021-06-27 21:25:29 +00:00
if (!ok)
{
2022-01-20 16:37:22 +00:00
AuMemory::Free(buf);
2021-06-27 21:25:29 +00:00
return nullptr;
}
ConsiderRehash();
if (init)
{
init(buf);
}
return buf;
}
void TLSViewImpl::ConsiderRehash()
{
try
{
// prevent Add, Remove, Add, Remove stalls
fence_++;
if ((fence_ % 10) == 0)
{
tls_.rehash(tls_.size());
}
}
catch (...)
{
}
}
}