LockFreeHashMap.h 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/NonCopyable.h>
  5. #include <Jolt/Core/Atomics.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// Allocator for a lock free hash map
  8. class LFHMAllocator : public NonCopyable
  9. {
  10. public:
  11. /// Destructor
  12. inline ~LFHMAllocator();
  13. /// Initialize the allocator
  14. /// @param inObjectStoreSizeBytes Number of bytes to reserve for all key value pairs
  15. inline void Init(uint inObjectStoreSizeBytes);
  16. /// Clear all allocations
  17. inline void Clear();
  18. /// Allocate a new block of data
  19. /// @param inBlockSize Size of block to allocate (will potentially return a smaller block if memory is full).
  20. /// @param ioBegin Should be the start of the first free byte in current memory block on input, will contain the start of the first free byte in allocated block on return.
  21. /// @param ioEnd Should be the byte beyond the current memory block on input, will contain the byte beyond the allocated block on return.
  22. inline void Allocate(uint32 inBlockSize, uint32 &ioBegin, uint32 &ioEnd);
  23. /// Convert a pointer to an offset
  24. template <class T>
  25. inline uint32 ToOffset(const T *inData) const;
  26. /// Convert an offset to a pointer
  27. template <class T>
  28. inline T * FromOffset(uint32 inOffset) const;
  29. private:
  30. uint8 * mObjectStore = nullptr; ///< This contains a contigous list of objects (possibly of varying size)
  31. uint32 mObjectStoreSizeBytes = 0; ///< The size of mObjectStore in bytes
  32. atomic<uint32> mWriteOffset { 0 }; ///< Next offset to write to in mObjectStore
  33. };
  34. /// Allocator context object for a lock free hash map that allocates a larger memory block at once and hands it out in smaller portions.
  35. /// This avoids contention on the atomic LFHMAllocator::mWriteOffset.
  36. class LFHMAllocatorContext : public NonCopyable
  37. {
  38. public:
  39. /// Construct a new allocator context
  40. inline LFHMAllocatorContext(LFHMAllocator &inAllocator, uint32 inBlockSize);
  41. /// @brief Allocate data block
  42. /// @param inSize Size of block to allocate.
  43. /// @param inAlignment Alignment of block to allocate.
  44. /// @param outWriteOffset Offset in buffer where block is located
  45. /// @return True if allocation succeeded
  46. inline bool Allocate(uint32 inSize, uint32 inAlignment, uint32 &outWriteOffset);
  47. private:
  48. LFHMAllocator & mAllocator;
  49. uint32 mBlockSize;
  50. uint32 mBegin = 0;
  51. uint32 mEnd = 0;
  52. };
  53. /// Very simple lock free hash map that only allows insertion, retrieval and provides a fixed amount of buckets and fixed storage.
  54. /// Note: This class currently assumes key and value are simple types that need no calls to the destructor.
  55. template <class Key, class Value>
  56. class LockFreeHashMap : public NonCopyable
  57. {
  58. public:
  59. using MapType = LockFreeHashMap<Key, Value>;
  60. /// Destructor
  61. explicit LockFreeHashMap(LFHMAllocator &inAllocator) : mAllocator(inAllocator) { }
  62. ~LockFreeHashMap();
  63. /// Initialization
  64. /// @param inMaxBuckets Max amount of buckets to use in the hashmap. Must be power of 2.
  65. void Init(uint32 inMaxBuckets);
  66. /// Remove all elements.
  67. /// Note that this cannot happen simultaneously with adding new elements.
  68. void Clear();
  69. /// Get the current amount of buckets that the map is using
  70. uint32 GetNumBuckets() const { return mNumBuckets; }
  71. /// Get the maximum amount of buckets that this map supports
  72. uint32 GetMaxBuckets() const { return mMaxBuckets; }
  73. /// Update the number of buckets. This must be done after clearing the map and cannot be done concurrently with any other operations on the map.
  74. /// Note that the number of buckets can never become bigger than the specified max buckets during initialization and that it must be a power of 2.
  75. void SetNumBuckets(uint32 inNumBuckets);
  76. /// A key / value pair that is inserted in the map
  77. class KeyValue
  78. {
  79. public:
  80. const Key & GetKey() const { return mKey; }
  81. Value & GetValue() { return mValue; }
  82. const Value & GetValue() const { return mValue; }
  83. private:
  84. template <class K, class V> friend class LockFreeHashMap;
  85. Key mKey; ///< Key for this entry
  86. uint32 mNextOffset; ///< Offset in mObjectStore of next KeyValue entry with same hash
  87. Value mValue; ///< Value for this entry + optionally extra bytes
  88. };
  89. /// Insert a new element, returns null if map full.
  90. /// Multiple threads can be inserting in the map at the same time.
  91. template <class... Params>
  92. inline KeyValue * Create(LFHMAllocatorContext &ioContext, const Key &inKey, uint64 inKeyHash, int inExtraBytes, Params &&... inConstructorParams);
  93. /// Find an element, returns null if not found
  94. inline const KeyValue * Find(const Key &inKey, uint64 inKeyHash) const;
  95. /// Value of an invalid handle
  96. const static uint32 cInvalidHandle = uint32(-1);
  97. /// Get convert key value pair to uint32 handle
  98. inline uint32 ToHandle(const KeyValue *inKeyValue) const;
  99. /// Convert uint32 handle back to key and value
  100. inline const KeyValue * FromHandle(uint32 inHandle) const;
  101. #ifdef JPH_ENABLE_ASSERTS
  102. /// Get the number of key value pairs that this map currently contains.
  103. /// Available only when asserts are enabled because adding elements creates contention on this atomic and negatively affects performance.
  104. inline uint32 GetNumKeyValues() const { return mNumKeyValues; }
  105. #endif // JPH_ENABLE_ASSERTS
  106. /// Get all key/value pairs
  107. inline void GetAllKeyValues(Array<const KeyValue *> &outAll) const;
  108. /// Non-const iterator
  109. struct Iterator
  110. {
  111. /// Comparison
  112. bool operator == (const Iterator &inRHS) const { return mMap == inRHS.mMap && mBucket == inRHS.mBucket && mOffset == inRHS.mOffset; }
  113. bool operator != (const Iterator &inRHS) const { return !(*this == inRHS); }
  114. /// Convert to key value pair
  115. KeyValue & operator * ();
  116. /// Next item
  117. Iterator & operator ++ ();
  118. MapType * mMap;
  119. uint32 mBucket;
  120. uint32 mOffset;
  121. };
  122. /// Iterate over the map, note that it is not safe to do this in parallel to Clear().
  123. /// It is safe to do this while adding elements to the map, but newly added elements may or may not be returned by the iterator.
  124. Iterator begin();
  125. Iterator end();
  126. #ifdef _DEBUG
  127. /// Output stats about this map to the log
  128. void TraceStats() const;
  129. #endif
  130. private:
  131. LFHMAllocator & mAllocator; ///< Allocator used to allocate key value pairs
  132. #ifdef JPH_ENABLE_ASSERTS
  133. atomic<uint32> mNumKeyValues = 0; ///< Number of key value pairs in the store
  134. #endif // JPH_ENABLE_ASSERTS
  135. atomic<uint32> * mBuckets = nullptr; ///< This contains the offset in mObjectStore of the first object with a particular hash
  136. uint32 mNumBuckets = 0; ///< Current number of buckets
  137. uint32 mMaxBuckets = 0; ///< Maximum number of buckets
  138. };
  139. JPH_NAMESPACE_END
  140. #include "LockFreeHashMap.inl"