Path: blob/master/thirdparty/jolt_physics/Jolt/Core/MutexArray.h
9906 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Core/NonCopyable.h>78JPH_NAMESPACE_BEGIN910/// A mutex array protects a number of resources with a limited amount of mutexes.11/// It uses hashing to find the mutex of a particular object.12/// The idea is that if the amount of threads is much smaller than the amount of mutexes13/// that there is a relatively small chance that two different objects map to the same mutex.14template <class MutexType>15class MutexArray : public NonCopyable16{17public:18/// Constructor, constructs an empty mutex array that you need to initialize with Init()19MutexArray() = default;2021/// Constructor, constructs an array with inNumMutexes entries22explicit MutexArray(uint inNumMutexes) { Init(inNumMutexes); }2324/// Destructor25~MutexArray() { delete [] mMutexStorage; }2627/// Initialization28/// @param inNumMutexes The amount of mutexes to allocate29void Init(uint inNumMutexes)30{31JPH_ASSERT(mMutexStorage == nullptr);32JPH_ASSERT(inNumMutexes > 0 && IsPowerOf2(inNumMutexes));3334mMutexStorage = new MutexStorage[inNumMutexes];35mNumMutexes = inNumMutexes;36}3738/// Get the number of mutexes that were allocated39inline uint GetNumMutexes() const40{41return mNumMutexes;42}4344/// Convert an object index to a mutex index45inline uint32 GetMutexIndex(uint32 inObjectIndex) const46{47Hash<uint32> hasher;48return hasher(inObjectIndex) & (mNumMutexes - 1);49}5051/// Get the mutex belonging to a certain object by index52inline MutexType & GetMutexByObjectIndex(uint32 inObjectIndex)53{54return mMutexStorage[GetMutexIndex(inObjectIndex)].mMutex;55}5657/// Get a mutex by index in the array58inline MutexType & GetMutexByIndex(uint32 inMutexIndex)59{60return mMutexStorage[inMutexIndex].mMutex;61}6263/// Lock all mutexes64void LockAll()65{66JPH_PROFILE_FUNCTION();6768MutexStorage *end = mMutexStorage + mNumMutexes;69for (MutexStorage *m = mMutexStorage; m < end; ++m)70m->mMutex.lock();71}7273/// Unlock all mutexes74void UnlockAll()75{76JPH_PROFILE_FUNCTION();7778MutexStorage *end = mMutexStorage + mNumMutexes;79for (MutexStorage *m = mMutexStorage; m < end; ++m)80m->mMutex.unlock();81}8283private:84/// Align the mutex to a cache line to ensure there is no false sharing (this is platform dependent, we do this to be safe)85struct alignas(JPH_CACHE_LINE_SIZE) MutexStorage86{87JPH_OVERRIDE_NEW_DELETE8889MutexType mMutex;90};9192MutexStorage * mMutexStorage = nullptr;93uint mNumMutexes = 0;94};9596JPH_NAMESPACE_END979899100