File tree Expand file tree Collapse file tree 2 files changed +30
-20
lines changed
Expand file tree Collapse file tree 2 files changed +30
-20
lines changed Original file line number Diff line number Diff line change @@ -8,76 +8,81 @@ This code was inspired by the farbot RealtimeObject implementation. See https://
88#include < array>
99#include < cassert>
1010
11+ namespace LUFS
12+ {
13+
1114template <typename T>
1215class DoubleBuffer
1316{
1417public:
1518 DoubleBuffer (const T& initialVal) : buffers{initialVal, initialVal}, realtimeCopy{initialVal} {}
16-
19+
1720 ~DoubleBuffer ()
1821 {
1922 // Busy bit should not be set
2023 assert ((control.load () & BusyBit) == 0 );
2124 }
22-
25+
2326 T& realtimeAquire ()
2427 {
2528 return realtimeCopy;
2629 }
27-
30+
2831 void realtimeRelease ()
2932 {
3033 // Set the busy bit and get the write index
3134 const int writeIndex = control.fetch_or (BusyBit) & IndexBit;
3235 buffers[writeIndex] = realtimeCopy;
33-
36+
3437 // Unset the busy bit, set the new data bit
3538 control.store ((writeIndex & IndexBit) | NewDataBit);
3639 }
37-
40+
3841 const T& nonRealtimeRead () const
3942 {
4043 int current = control.load ();
41-
44+
4245 if (current & NewDataBit)
4346 {
4447 int newValue;
45-
48+
4649 // CAS loop to spin while busy bit is set, then set the new buffer to write to
4750 do
4851 {
4952 current &= ~BusyBit;
5053 newValue = (current ^ IndexBit) & IndexBit;
5154 }
5255 while (!control.compare_exchange_weak (current, newValue));
53-
56+
5457 current = newValue;
5558 }
56-
59+
5760 // Return the last buffer that was written to
5861 return buffers[(current & IndexBit) ^ 0x1 ];
5962 }
60-
63+
6164 // This is not realtime safe with the other calls
6265 void reset (const T& newValue)
6366 {
6467 assert ((control.load () & BusyBit) == 0 );
65-
68+
6669 buffers[0 ] = newValue;
6770 buffers[1 ] = newValue;
6871 realtimeCopy = newValue;
6972 }
70-
73+
7174private:
72- enum
73- {
74- IndexBit = (1 << 0 ),
75- NewDataBit = (1 << 1 ),
75+ enum
76+ {
77+ IndexBit = (1 << 0 ),
78+ NewDataBit = (1 << 1 ),
7679 BusyBit = (1 << 2 )
7780 };
78-
81+
7982 mutable std::atomic<int > control;
80-
83+
8184 std::array<T, 2 > buffers;
8285 T realtimeCopy;
83- };
86+ };
87+
88+ }
Original file line number Diff line number Diff line change 33#include < atomic>
44#include < thread>
55
6+ namespace LUFS
7+ {
8+
69class SpinLock
710{
811public:
@@ -30,4 +33,6 @@ class SpinLock
3033
3134private:
3235 std::atomic<bool > lockedFlag = false ;
33- };
36+ };
37+
38+ }
You can’t perform that action at this time.
0 commit comments