| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#pragma once |
| 6 |
|
| 7 |
#include <Jolt/Core/NonCopyable.h> |
| 8 |
|
| 9 |
JPH_NAMESPACE_BEGIN |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
template <class MutexType> |
| 16 |
class MutexArray : public NonCopyable |
| 17 |
{ |
| 18 |
public: |
| 19 |
|
| 20 |
MutexArray() = default; |
| 21 |
|
| 22 |
|
| 23 |
explicit MutexArray(uint inNumMutexes) { Init(inNumMutexes); } |
| 24 |
|
| 25 |
|
| 26 |
~MutexArray() { delete [] mMutexStorage; } |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
void Init(uint inNumMutexes) |
| 31 |
{ |
| 32 |
JPH_ASSERT(mMutexStorage == nullptr); |
| 33 |
JPH_ASSERT(inNumMutexes > 0 && IsPowerOf2(inNumMutexes)); |
| 34 |
|
| 35 |
mMutexStorage = new MutexStorage[inNumMutexes]; |
| 36 |
mNumMutexes = inNumMutexes; |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
inline uint GetNumMutexes() const |
| 41 |
{ |
| 42 |
return mNumMutexes; |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
inline uint32 GetMutexIndex(uint32 inObjectIndex) const |
| 47 |
{ |
| 48 |
Hash<uint32> hasher; |
| 49 |
return hasher(inObjectIndex) & (mNumMutexes - 1); |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
inline MutexType & GetMutexByObjectIndex(uint32 inObjectIndex) |
| 54 |
{ |
| 55 |
return mMutexStorage[GetMutexIndex(inObjectIndex)].mMutex; |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
inline MutexType & GetMutexByIndex(uint32 inMutexIndex) |
| 60 |
{ |
| 61 |
return mMutexStorage[inMutexIndex].mMutex; |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
void LockAll() |
| 66 |
{ |
| 67 |
JPH_PROFILE_FUNCTION(); |
| 68 |
|
| 69 |
MutexStorage *end = mMutexStorage + mNumMutexes; |
| 70 |
for (MutexStorage *m = mMutexStorage; m < end; ++m) |
| 71 |
m->mMutex.lock(); |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
void UnlockAll() |
| 76 |
{ |
| 77 |
JPH_PROFILE_FUNCTION(); |
| 78 |
|
| 79 |
MutexStorage *end = mMutexStorage + mNumMutexes; |
| 80 |
for (MutexStorage *m = mMutexStorage; m < end; ++m) |
| 81 |
m->mMutex.unlock(); |
| 82 |
} |
| 83 |
|
| 84 |
private: |
| 85 |
|
| 86 |
struct alignas(JPH_CACHE_LINE_SIZE) MutexStorage |
| 87 |
{ |
| 88 |
JPH_OVERRIDE_NEW_DELETE |
| 89 |
|
| 90 |
MutexType mMutex; |
| 91 |
}; |
| 92 |
|
| 93 |
MutexStorage * mMutexStorage = nullptr; |
| 94 |
uint mNumMutexes = 0; |
| 95 |
}; |
| 96 |
|
| 97 |
JPH_NAMESPACE_END |
| 98 |
|