LockFreeHashMap.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/NonCopyable.h>
  5. #include <atomic>
  6. namespace JPH {
  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 allocae
  43. /// @param outWriteOffset Offset in buffer where block is located
  44. /// @return True if allocation succeeded
  45. inline bool Allocate(uint32 inSize, uint32 &outWriteOffset);
  46. private:
  47. LFHMAllocator & mAllocator;
  48. uint32 mBlockSize;
  49. uint32 mBegin = 0;
  50. uint32 mEnd = 0;
  51. };
  52. /// Very simple lock free hash map that only allows insertion, retrieval and provides a fixed amount of buckets and fixed storage.
  53. /// Note: This class currently assumes key and value are simple types that need no calls to the destructor.
  54. template <class Key, class Value>
  55. class LockFreeHashMap : public NonCopyable
  56. {
  57. public:
  58. using MapType = LockFreeHashMap<Key, Value>;
  59. /// Destructor
  60. explicit LockFreeHashMap(LFHMAllocator &inAllocator) : mAllocator(inAllocator) { }
  61. ~LockFreeHashMap();
  62. /// Initialization
  63. /// @param inMaxBuckets Max amount of buckets to use in the hashmap. Must be power of 2.
  64. void Init(uint32 inMaxBuckets);
  65. /// Remove all elements.
  66. /// Note that this cannot happen simultaneously with adding new elements.
  67. void Clear();
  68. /// Get the current amount of buckets that the map is using
  69. uint32 GetNumBuckets() const { return mNumBuckets; }
  70. /// Get the maximum amount of buckets that this map supports
  71. uint32 GetMaxBuckets() const { return mMaxBuckets; }
  72. /// 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.
  73. /// 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.
  74. void SetNumBuckets(uint32 inNumBuckets);
  75. /// A key / value pair that is inserted in the map
  76. class KeyValue
  77. {
  78. public:
  79. const Key & GetKey() const { return mKey; }
  80. Value & GetValue() { return mValue; }
  81. const Value & GetValue() const { return mValue; }
  82. private:
  83. template <class K, class V> friend class LockFreeHashMap;
  84. Key mKey; ///< Key for this entry
  85. uint32 mNextOffset; ///< Offset in mObjectStore of next KeyValue entry with same hash
  86. Value mValue; ///< Value for this entry + optionally extra bytes
  87. };
  88. /// Insert a new element, returns null if map full.
  89. /// Multiple threads can be inserting in the map at the same time.
  90. template <class... Params>
  91. inline KeyValue * Create(LFHMAllocatorContext &ioContext, const Key &inKey, size_t inKeyHash, int inExtraBytes, Params &&... inConstructorParams);
  92. /// Find an element, returns null if not found
  93. inline const KeyValue * Find(const Key &inKey, size_t inKeyHash) const;
  94. /// Value of an invalid handle
  95. const static uint32 cInvalidHandle = uint32(-1);
  96. /// Get convert key value pair to uint32 handle
  97. inline uint32 ToHandle(const KeyValue *inKeyValue) const;
  98. /// Convert uint32 handle back to key and value
  99. inline const KeyValue * FromHandle(uint32 inHandle) const;
  100. #ifdef JPH_ENABLE_ASSERTS
  101. /// Get the number of key value pairs that this map currently contains.
  102. /// Available only when asserts are enabled because adding elements creates contention on this atomic and negatively affects performance.
  103. inline uint32 GetNumKeyValues() const { return mNumKeyValues; }
  104. #endif // JPH_ENABLE_ASSERTS
  105. /// Get all key/value pairs
  106. inline void GetAllKeyValues(vector<const KeyValue *> &outAll) const;
  107. /// Non-const iterator
  108. struct Iterator
  109. {
  110. /// Comparison
  111. bool operator == (const Iterator &inRHS) const { return mMap == inRHS.mMap && mBucket == inRHS.mBucket && mOffset == inRHS.mOffset; }
  112. bool operator != (const Iterator &inRHS) const { return !(*this == inRHS); }
  113. /// Convert to key value pair
  114. KeyValue & operator * ();
  115. /// Next item
  116. Iterator & operator ++ ();
  117. MapType * mMap;
  118. uint32 mBucket;
  119. uint32 mOffset;
  120. };
  121. /// Iterate over the map, note that it is not safe to do this in parallel to Clear().
  122. /// 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.
  123. Iterator begin();
  124. Iterator end();
  125. #ifdef _DEBUG
  126. /// Output stats about this map to the log
  127. void TraceStats() const;
  128. #endif
  129. private:
  130. LFHMAllocator & mAllocator; ///< Allocator used to allocate key value pairs
  131. #ifdef JPH_ENABLE_ASSERTS
  132. atomic<uint32> mNumKeyValues = 0; ///< Number of key value pairs in the store
  133. #endif // JPH_ENABLE_ASSERTS
  134. atomic<uint32> * mBuckets = nullptr; ///< This contains the offset in mObjectStore of the first object with a particular hash
  135. uint32 mNumBuckets = 0; ///< Current number of buckets
  136. uint32 mMaxBuckets = 0; ///< Maximum number of buckets
  137. };
  138. } // JPH
  139. #include "LockFreeHashMap.inl"