Foundation
Loading...
Searching...
No Matches
Pool.hpp
Go to the documentation of this file.
1#pragma once
2#include <Core/Container.hpp>
3#include "Queue.hpp"
4namespace Foundation::Atomics {
5 using namespace Core;
15 template<typename K, typename V, typename Tombstone = V>
16 class Pool {
17 const size_t mCapacity;
20 // Yes - there is Vector<bool>. If only you know the horror to
21 // synchronize a bitset across threads...
23 public:
29 Pool(size_t size, Allocator* alloc) :
30 mCapacity(size), mKeys(size, alloc), mValues(size, alloc), mBitmap(size, alloc)
31 {
32 // Allocate all the keys that can be possibly produced
33 auto writer = mKeys.CreateWriter();
34 for (size_t i = 0; i < size; i++)
35 writer.Push(i);
36 }
40 bool Contains(K key) const {
41 return key < mValues.size() && mBitmap[key];
42 }
47 V& At(K key) {
48 CHECK_MSG(Contains(key), "Key not allocated");
49 return mValues[key];
50 }
54 V const& At(K key) const {
55 CHECK_MSG(Contains(key), "Key not allocated");
56 return mValues[key];
57 }
58 const K Pop()
59 {
60 K key;
61 CHECK_MSG(mKeys.CreateReader().Pop(key), "Key pool exhausted");
62 mBitmap[key] = true;
63 return key;
64 }
69 {
70 K key = Pop();
71 mBitmap[key] = true;
72 return { key, mValues[key] };
73 }
77 void Free(K key) {
78 CHECK_MSG(Contains(key), "Key {} is invalid", key);
80 mBitmap[key] = false;
81 CHECK_MSG(mKeys.CreateWriter().Push(key), "Key pool full");
82 }
83 };
84}
#define CHECK_MSG(expr, format_str,...)
Definition Logging.hpp:31
Reader CreateReader()
Create a Reader for concurrent popping.
Definition Queue.hpp:180
Writer CreateWriter()
Create a Writer for concurrent pushing.
Definition Queue.hpp:138
Atomic, bounded object pool with O(1) value mapping.
Definition Pool.hpp:16
const K Pop()
Definition Pool.hpp:58
bool Contains(K key) const
Checks if the specified key exists and has a value.
Definition Pool.hpp:40
MPMCQueue< K > mKeys
Definition Pool.hpp:18
Vector< V > mValues
Definition Pool.hpp:19
const Pair< K, V & > PopPair()
Allocates a Key that returns a pair of key and value reference.
Definition Pool.hpp:68
void Free(K key)
Frees the value associated with the specified key.
Definition Pool.hpp:77
const size_t mCapacity
Definition Pool.hpp:17
V & At(K key)
Retrieves a reference to the value associated with the given key. NOTE: Calling this function with a ...
Definition Pool.hpp:47
V const & At(K key) const
Retrieves a const reference to the value associated with the given key.
Definition Pool.hpp:54
Vector< char > mBitmap
Definition Pool.hpp:22
Pool(size_t size, Allocator *alloc)
Constructs a FreeList with the specified capacity and allocator.
Definition Pool.hpp:29
General Purpose Allocator (GPA) interface.
Definition Allocator.hpp:24
Lock-free atomic primitives and implementations of data structures.
Definition Atomic.hpp:22
std::unique_ptr< T, StlDeleter< T > > UniquePtr
std::unique_ptr with custom deleter that uses a Foundation::Core::Allocator to deallocate memory.
Definition Allocator.hpp:161