25566372fdd172fef9f9bf79bd2ba4ae42013e18
[junction.git] / junction / striped / ConditionBank.h
1 /*------------------------------------------------------------------------
2   Junction: Concurrent data structures in C++
3   Copyright (c) 2016 Jeff Preshing
4
5   Distributed under the Simplified BSD License.
6   Original location: https://github.com/preshing/junction
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the LICENSE file for more information.
11 ------------------------------------------------------------------------*/
12
13 #ifndef JUNCTION_STRIPED_CONDITIONBANK_H
14 #define JUNCTION_STRIPED_CONDITIONBANK_H
15
16 #include <junction/Core.h>
17 #include <junction/striped/ConditionPair.h>
18
19 #if JUNCTION_USE_STRIPING
20
21 //-----------------------------------
22 // Striping enabled
23 //-----------------------------------
24 #include <turf/impl/Mutex_SpinLock.h>
25 #include <turf/Util.h>
26
27 namespace junction {
28 namespace striped {
29
30 class ConditionBank {
31 private:
32     static const ureg SizeMask = 1023;
33     turf::Mutex_SpinLock m_initSpinLock;
34     turf::Atomic<ConditionPair*> m_pairs;
35
36     ConditionPair* initialize();
37
38 public:
39     ConditionPair& get(void* ptr) {
40         ConditionPair* pairs = m_pairs.load(turf::Consume);
41         if (!pairs) {
42             pairs = initialize();
43         }
44         ureg index = turf::util::avalanche(uptr(ptr)) & SizeMask;
45         return pairs[index];
46     }
47 };
48
49 extern ConditionBank DefaultConditionBank;
50
51 } // namespace striped
52 } // namespace junction
53
54 #define JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
55 #define JUNCTION_STRIPED_CONDITIONBANK_GET(objectPtr) (junction::striped::DefaultConditionBank.get(objectPtr))
56
57 #else // JUNCTION_USE_STRIPING
58
59 //-----------------------------------
60 // Striping disabled
61 //-----------------------------------
62 #define JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER() junction::striped::ConditionPair m_conditionPair;
63 #define JUNCTION_STRIPED_CONDITIONBANK_GET(objectPtr) ((objectPtr)->m_conditionPair)
64
65 #endif // JUNCTION_USE_STRIPING
66
67 #endif // JUNCTION_STRIPED_CONDITIONBANK_H