Debian Codegraph @

thirdparty/jolt_physics/Jolt/Core/MutexArray.h

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #pragma once
6
7 #include <Jolt/Core/NonCopyable.h>
8
9 JPH_NAMESPACE_BEGIN
10
11 /// A mutex array protects a number of resources with a limited amount of mutexes.
12 /// It uses hashing to find the mutex of a particular object.
13 /// The idea is that if the amount of threads is much smaller than the amount of mutexes
14 /// that there is a relatively small chance that two different objects map to the same mutex.
15 template <class MutexType>
16 class MutexArray : public NonCopyable
17 {
18 public:
19 /// Constructor, constructs an empty mutex array that you need to initialize with Init()
20 MutexArray() = default;
21
22 /// Constructor, constructs an array with inNumMutexes entries
23 explicit MutexArray(uint inNumMutexes) { Init(inNumMutexes); }
24
25 /// Destructor
26 ~MutexArray() { delete [] mMutexStorage; }
27
28 /// Initialization
29 /// @param inNumMutexes The amount of mutexes to allocate
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 /// Get the number of mutexes that were allocated
40 inline uint GetNumMutexes() const
41 {
42 return mNumMutexes;
43 }
44
45 /// Convert an object index to a mutex index
46 inline uint32 GetMutexIndex(uint32 inObjectIndex) const
47 {
48 Hash<uint32> hasher;
49 return hasher(inObjectIndex) & (mNumMutexes - 1);
50 }
51
52 /// Get the mutex belonging to a certain object by index
53 inline MutexType & GetMutexByObjectIndex(uint32 inObjectIndex)
54 {
55 return mMutexStorage[GetMutexIndex(inObjectIndex)].mMutex;
56 }
57
58 /// Get a mutex by index in the array
59 inline MutexType & GetMutexByIndex(uint32 inMutexIndex)
60 {
61 return mMutexStorage[inMutexIndex].mMutex;
62 }
63
64 /// Lock all mutexes
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 /// Unlock all mutexes
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 /// Align the mutex to a cache line to ensure there is no false sharing (this is platform dependent, we do this to be safe)
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