-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllocatorFactory.cpp
More file actions
36 lines (27 loc) · 1.05 KB
/
AllocatorFactory.cpp
File metadata and controls
36 lines (27 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "AllocatorFactory.h"
#include <shared_mutex>
#include <thread>
#include <unordered_map>
#include <assert.h>
const AllocatorFactory::DefaultAllocator& AllocatorFactory::get_current_thread_allocator()
{
static std::shared_mutex protect;
static std::unordered_map<std::thread::id, DefaultAllocator> allocators;
const std::thread::id threadId = std::this_thread::get_id();
{
std::shared_lock<std::shared_mutex> lockForRead(protect);
const auto iter = allocators.find(threadId);
if (iter != allocators.end())
{
return iter->second;
}
}
const size_t heapId = static_cast<size_t>(std::hash<std::thread::id>{}(threadId));
const DefaultAllocator newAllocator(heapId);
{
std::unique_lock<std::shared_mutex> lockForWrite(protect);
const auto result = allocators.emplace(threadId, newAllocator);
assert(result.second && "Insertion should always succeed since nobody else except current thread can insert the same key");
return result.first->second;
}
}