MutexArray.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. namespace JPH {
  5. /// A mutex array protects a number of resources with a limited amount of mutexes.
  6. /// It uses hashing to find the mutex of a particular object.
  7. /// The idea is that if the amount of threads is much smaller than the amount of mutexes
  8. /// that there is a relatively small chance that two different objects map to the same mutex.
  9. template <class MutexType, int NumMutexesArg>
  10. class MutexArray
  11. {
  12. public:
  13. /// Number of mutexes used to protect the underlying resources.
  14. static constexpr int NumMutexes = NumMutexesArg;
  15. /// Convert an object index to a mutex index
  16. inline uint32 GetMutexIndex(uint32 inObjectIndex) const
  17. {
  18. std::hash<uint32> hasher;
  19. static_assert(IsPowerOf2(NumMutexes), "Number of mutexes must be power of 2");
  20. return hasher(inObjectIndex) & (NumMutexes - 1);
  21. }
  22. /// Get the mutex belonging to a certain object by index
  23. inline MutexType & GetMutexByObjectIndex(uint32 inObjectIndex)
  24. {
  25. return mMutexStorage[GetMutexIndex(inObjectIndex)].mMutex;
  26. }
  27. /// Get a mutex by index in the array
  28. inline MutexType & GetMutexByIndex(uint32 inMutexIndex)
  29. {
  30. return mMutexStorage[inMutexIndex].mMutex;
  31. }
  32. /// Lock all mutexes
  33. void LockAll()
  34. {
  35. JPH_PROFILE_FUNCTION();
  36. for (MutexStorage &m : mMutexStorage)
  37. m.mMutex.lock();
  38. }
  39. /// Unlock all mutexes
  40. void UnlockAll()
  41. {
  42. JPH_PROFILE_FUNCTION();
  43. for (MutexStorage &m : mMutexStorage)
  44. m.mMutex.unlock();
  45. }
  46. private:
  47. /// Align the mutex to a cache line to ensure there is no false sharing (this is platform dependent, we do this to be safe)
  48. struct alignas(JPH_CACHE_LINE_SIZE) MutexStorage
  49. {
  50. MutexType mMutex;
  51. };
  52. MutexStorage mMutexStorage[NumMutexes];
  53. };
  54. } // JPH