LockFreeHashMap.h 6.7 KB

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