UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
TripleBufferedData.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#include "Templates/Atomic.h"
7
8namespace Chaos
9{
71 template <class DataType>
73 {
74 public:
76 : ProducerThreadBuffer(&Buffers[0])
77 , ConsumerThreadBuffer(&Buffers[1])
78 , Interchange(&Buffers[2])
79 , Counter(0)
80 , LastId(0)
81 {}
82
115 {
116 ProducerThreadBuffer = Interchange.Exchange(ProducerThreadBuffer);
117 if (!ProducerThreadBuffer->Value)
118 {
119 ProducerThreadBuffer->Value = TUniquePtr<DataType>(new DataType());
120 }
121 ProducerThreadBuffer->Id = ++Counter; // First value is 1, will overflow.
122 return ProducerThreadBuffer->Value.Get();
123 }
124
153 {
154 ConsumerThreadBuffer = Interchange.Exchange(ConsumerThreadBuffer);
155 if (ConsumerThreadBuffer->Id <= LastId &&
156 LastId - ConsumerThreadBuffer->Id < TNumericLimits<uint32>::Max()) // Detect overflows
157 {
158 return nullptr;
159 }
160 LastId = ConsumerThreadBuffer->Id;
161 return ConsumerThreadBuffer->Value.Get();
162 }
163
164 private:
165 // Non-copyable and non-movable, due to TAtomic member.
168 TTripleBufferedData& operator=(TTripleBufferedData&&) = delete;
169 TTripleBufferedData& operator=(const TTripleBufferedData&) = delete;
170
171 struct DataTypeWrapper
172 {
173 DataTypeWrapper()
174 : Value(nullptr)
175 , Id(0)
176 {}
177 DataTypeWrapper(const DataTypeWrapper&) = delete;
178 DataTypeWrapper(DataTypeWrapper&& Other)
179 : Value(MoveTemp(Other.Value))
180 , Id(MoveTemp(Other.Id))
181 {}
182
183 void operator=(const DataTypeWrapper& Other) = delete;
184
185 // Depending on the use case, it may be useful to store DataType
186 // instances via shared pointer so that the thread that doesn't
187 // own the TripleBufferedData instance, can retain ownership of
188 // this memory after this class goes out of scope.
190 uint64 Id;
191 };
192
193 DataTypeWrapper Buffers[3] = { DataTypeWrapper(), DataTypeWrapper(), DataTypeWrapper() };
194 DataTypeWrapper* ProducerThreadBuffer;
195 DataTypeWrapper* ConsumerThreadBuffer;
196 TAtomic<DataTypeWrapper*> Interchange;
197 uint64 Counter; // Only accessed by producer thread
198 uint64 LastId; // Only accessed by consumer thread
199 };
200} // namespace Chaos
FPlatformTypes::uint64 uint64
A 64-bit unsigned integer.
Definition Platform.h:1117
UE_INTRINSIC_CAST UE_REWRITE constexpr std::remove_reference_t< T > && MoveTemp(T &&Obj) noexcept
Definition UnrealTemplate.h:520
Definition TripleBufferedData.h:73
DataType * ExchangeConsumerBuffer()
Definition TripleBufferedData.h:152
DataType * ExchangeProducerBuffer()
Definition TripleBufferedData.h:114
TTripleBufferedData()
Definition TripleBufferedData.h:75
Definition Atomic.h:538
Definition UniquePtr.h:107
Definition SkeletalMeshComponent.h:307
@ Id
Definition Protocol0.h:17
Definition NumericLimits.h:41