UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
Future.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#include "CoreTypes.h"
9#include "Misc/Timespan.h"
11#include "Misc/DateTime.h"
12#include "HAL/Event.h"
13#include "HAL/PooledSyncEvent.h"
14#include "Misc/ScopeLock.h"
15#include "Templates/Models.h"
16#include <type_traits>
17
18template<typename ResultType> class TFuture;
19template<typename ResultType> class TSharedFuture;
20template<typename ResultType> class TPromise;
21
22namespace UE::Core::Private
23{
24 // A concept check for a type being callable
26 {
27 template <typename Type>
28 auto Requires(Type& Callable, int32 Val) -> decltype(
29 Callable(Val)
30 );
31 };
32}
33
38{
39public:
40
42 FFutureState() = default;
43
50 : CompletionCallback(MoveTemp(InCompletionCallback))
51 {
52 }
53
54public:
55
62 bool IsComplete() const
63 {
64 return bComplete;
65 }
66
74 bool WaitFor(const FTimespan& Duration) const
75 {
76 if (CompletionEvent->Wait(Duration))
77 {
78 return true;
79 }
80
81 return false;
82 }
83
89 {
91 if (!bShouldJustRun)
92 {
93 FScopeLock Lock(&Mutex);
95 if (!bShouldJustRun)
96 {
97 CompletionCallback = MoveTemp(Continuation);
98 }
99 }
101 {
102 Continuation();
103 }
104 }
105
106protected:
107
110 {
112 {
113 FScopeLock Lock(&Mutex);
114 Continuation = MoveTemp(CompletionCallback);
115 bComplete = true;
116 }
117 CompletionEvent->Trigger();
118
119 if (Continuation)
120 {
121 Continuation();
122 }
123 }
124
125private:
127 mutable FCriticalSection Mutex;
128
130 TUniqueFunction<void()> CompletionCallback;
131
133 FPooledSyncEvent CompletionEvent{ true };
134
136 TAtomic<bool> bComplete{ false };
137};
138
139
143template<typename ResultType>
145 : public FFutureState
146{
147public:
151
154 : FFutureState()
155 { }
156
158 {
159 if (IsComplete())
160 {
161 Result.DestroyUnchecked();
162 }
163 }
164
170 TFutureState(TUniqueFunction<void()>&& CompletionCallback)
171 : FFutureState(MoveTemp(CompletionCallback))
172 { }
173
174public:
175
183 {
184 while (!IsComplete())
185 {
187 }
188
189 return Result.GetUnchecked();
190 }
192 {
193 return const_cast<TFutureState*>(this)->GetResult();
194 }
195
202 template<typename... ArgTypes>
203 void EmplaceResult(ArgTypes&&... Args)
204 {
205 check(!IsComplete());
206 Result.EmplaceUnchecked(Forward<ArgTypes>(Args)...);
207 MarkComplete();
208 }
209
210private:
211
214};
215
216/* TFuture
217*****************************************************************************/
218
222template <typename ResultType>
224{
225protected:
227
228public:
232
240 requires (!std::is_object_v<ResultType>)
241 {
242 return this->GetState()->GetResult();
243 }
245 requires (std::is_object_v<ResultType>)
246 {
247 return this->GetState()->GetResult();
248 }
249
256 bool IsReady() const
257 {
258 return State.IsValid() ? State->IsComplete() : false;
259 }
260
267 bool IsValid() const
268 {
269 return State.IsValid();
270 }
271
280 void Wait() const
281 {
282 if (State.IsValid())
283 {
284 while (!WaitFor(FTimespan::MaxValue()));
285 }
286 }
287
295 bool WaitFor(const FTimespan& Duration) const
296 {
297 return State.IsValid() ? State->WaitFor(Duration) : false;
298 }
299
307 bool WaitUntil(const FDateTime& Time) const
308 {
309 return WaitFor(Time - FDateTime::UtcNow());
310 }
311
312protected:
313
315 TFutureBase() = default;
316
327 : State(InState)
328 {
329 }
330
337 {
338 // if you hit this assertion then your future has an invalid state.
339 // this happens if you have an uninitialized future or if you moved
340 // it to another instance.
341 check(State.IsValid());
342
343 return State;
344 }
345
353 template<typename Func>
354 auto Then(Func Continuation);
355
363 template<typename Func>
364 auto Next(Func Continuation);
365
371 void Reset()
372 {
373 if (IsValid())
374 {
375 this->State->SetContinuation(nullptr);
376 this->State.Reset();
377 }
378 }
379
380private:
381
384};
385
386
390template<typename ResultType>
391class TFuture final
392 : public TFutureBase<ResultType>
393{
394 template <typename>
395 friend class TPromise;
396
397 template <typename>
398 friend class TFutureBase;
399
401
402 using MutableResultType = typename BaseType::MutableResultType;
403 using ConstResultType = typename BaseType::ConstResultType;
404 using RvalueResultType = typename BaseType::RvalueResultType;
405
406public:
407
409 TFuture() = default;
410
411 // Movable-only
412 TFuture(TFuture&&) = default;
413 TFuture(const TFuture&) = delete;
414 TFuture& operator=(TFuture&&) = default;
415 TFuture& operator=(const TFuture&) = delete;
416 ~TFuture() = default;
417
424 MutableResultType GetMutable()
425 requires (!std::is_object_v<ResultType>)
426 {
427 return (MutableResultType)this->Get();
428 }
429 MutableResultType GetMutable() UE_LIFETIMEBOUND
430 requires (std::is_object_v<ResultType>)
431 {
432 return (MutableResultType)this->Get();
433 }
434
441 ResultType Consume()
442 {
443 TFuture Local(MoveTemp(*this));
444 return (RvalueResultType)Local.Get();
445 }
446
456
462
468
474
475private:
476 // Forward constructors
478};
479
480
481/* TSharedFuture
482*****************************************************************************/
483
487template<typename ResultType>
488class TSharedFuture final
489 : public TFutureBase<ResultType>
490{
491 template <typename>
492 friend class TFuture;
493
495
496 using MutableResultType = typename BaseType::MutableResultType;
497 using ConstResultType = typename BaseType::ConstResultType;
498 using RvalueResultType = typename BaseType::RvalueResultType;
499
500public:
501
503 TSharedFuture() = default;
504
511 : BaseType(MoveTemp(Future))
512 { }
513
520 ConstResultType Get() const
521 {
522 // This forwarding function is necessary to 'cancel' the UE_LIFETIMEBOUND of the base class, as
523 // other shared futures can keep the object alive.
524 return BaseType::Get();
525 }
526
527private:
528 // Forward constructors
530};
531
532
533/* TPromise
534*****************************************************************************/
535
539template<typename ResultType>
540class TPromise final
541{
543
544 // This is necessary because we can't form references to void for the parameter of Set().
545 using SetType = std::conditional_t<std::is_void_v<ResultType>, int, ResultType>;
546
547public:
548
551 : State(MakeShared<TFutureState<ResultType>>())
552 {
553 }
554
560 TPromise(TUniqueFunction<void()>&& CompletionCallback)
561 : State(MakeShared<TFutureState<ResultType>>(MoveTemp(CompletionCallback)))
562 {
563 }
564
565 // Movable-only
566 TPromise(TPromise&& Other) = default;
567 TPromise(const TPromise& Other) = delete;
569 TPromise& operator=(const TPromise& Other) = delete;
570
573 {
574 if (State.IsValid())
575 {
576 // if you hit this assertion then your promise never had its result
577 // value set. broken promises are considered programming errors.
578 check(State->IsComplete());
579 }
580 }
581
588 {
589 check(!bFutureRetrieved);
590 bFutureRetrieved = true;
591
592 return TFuture<ResultType>(this->GetState());
593 }
594
603 inline void SetValue(const SetType& Result)
604 requires(!std::is_void_v<ResultType>)
605 {
606 EmplaceValue(Result);
607 }
608 inline void SetValue(SetType&& Result)
609 requires(!std::is_void_v<ResultType> && !std::is_lvalue_reference_v<ResultType>)
610 {
611 EmplaceValue(MoveTemp(Result));
612 }
613 inline void SetValue()
614 requires(std::is_void_v<ResultType>)
615 {
616 EmplaceValue();
617 }
618
627 template <typename... ArgTypes>
628 void EmplaceValue(ArgTypes&&... Args)
629 {
630 this->GetState()->EmplaceResult(Forward<ArgTypes>(Args)...);
631 }
632
633protected:
640 {
641 // if you hit this assertion then your promise has an invalid state.
642 // this happens if you move the promise to another instance.
643 check(State.IsValid());
644
645 return State;
646 }
647
648private:
651
653 bool bFutureRetrieved = false;
654};
655
656/* TFuture::Then
657*****************************************************************************/
658
660{
664 template<typename Func, typename ParamType, typename ResultType>
665 inline void SetPromiseValue(TPromise<ResultType>& Promise, Func& Function, TFuture<ParamType>&& Param)
666 {
667 Promise.SetValue(Function(MoveTemp(Param)));
668 }
669 template<typename Func, typename ParamType>
670 inline void SetPromiseValue(TPromise<void>& Promise, Func& Function, TFuture<ParamType>&& Param)
671 {
672 Function(MoveTemp(Param));
673 Promise.SetValue();
674 }
675}
676
677// Then implementation
678template<typename ResultType>
679template<typename Func>
680auto TFutureBase<ResultType>::Then(Func Continuation) //-> TFuture<decltype(Continuation(MoveTemp(TFuture<ResultType>())))>
681{
682 check(IsValid());
683 using ReturnValue = decltype(Continuation(MoveTemp(TFuture<ResultType>())));
684
685 TPromise<ReturnValue> Promise;
686 TFuture<ReturnValue> FutureResult = Promise.GetFuture();
687 TUniqueFunction<void()> Callback = [PromiseCapture = MoveTemp(Promise), ContinuationCapture = MoveTemp(Continuation), StateCapture = this->State]() mutable
688 {
690 };
691
692 // This invalidate this future.
694 MovedState->SetContinuation(MoveTemp(Callback));
695 return FutureResult;
696}
697
698// Next implementation
699template<typename ResultType>
700template<typename Func>
701auto TFutureBase<ResultType>::Next(Func Continuation) //-> TFuture<decltype(Continuation(Consume()))>
702{
703 return this->Then([Continuation = MoveTemp(Continuation)](TFuture<ResultType> Self) mutable
704 {
705 if constexpr (std::is_void_v<ResultType>)
706 {
707 Self.Consume();
709 {
710 UE_STATIC_DEPRECATE(5.6, true, "Passing continuations to TFuture<void>::Next which take int parameters has been deprecated - please remove the parameter.");
711 return Continuation(1);
712 }
713 else
714 {
715 return Continuation();
716 }
717 }
718 else
719 {
720 return Continuation(Self.Consume());
721 }
722 });
723}
724
726template<typename ResultType, typename... ArgTypes>
728{
729 TPromise<ResultType> Promise;
730 Promise.EmplaceValue(Forward<ArgTypes>(Args)...);
731 return Promise;
732}
733
734#if UE_ENABLE_INCLUDE_ORDER_DEPRECATED_IN_5_7
735#include "Templates/Requires.h"
736#endif
OODEFFUNC typedef void(OODLE_CALLBACK t_fp_OodleCore_Plugin_Free)(void *ptr)
#define check(expr)
Definition AssertionMacros.h:314
return Self
Definition CocoaThread.cpp:337
#define UE_STATIC_DEPRECATE(Version, bExpression, Message)
Definition CoreMiscDefines.h:420
#define UE_LIFETIMEBOUND
Definition Platform.h:812
FPlatformTypes::int32 int32
A 32-bit signed integer.
Definition Platform.h:1125
TSharedRef< InObjectType, InMode > MakeShared(InArgTypes &&... Args)
Definition SharedPointer.h:2009
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
UE::FPlatformRecursiveMutex FCriticalSection
Definition CriticalSection.h:53
TPromise< ResultType > MakeFulfilledPromise(ArgTypes &&... Args)
Definition Future.h:727
float Val(const FString &Value)
Definition UnrealMath.cpp:3163
UE_INTRINSIC_CAST UE_REWRITE constexpr std::remove_reference_t< T > && MoveTemp(T &&Obj) noexcept
Definition UnrealTemplate.h:520
FRWLock Lock
Definition UnversionedPropertySerialization.cpp:921
virtual bool Wait(uint32 WaitTime, const bool bIgnoreThreadIdleStats=false)=0
virtual void Trigger()=0
Definition Future.h:38
FFutureState(TUniqueFunction< void()> &&InCompletionCallback)
Definition Future.h:49
void SetContinuation(TUniqueFunction< void()> &&Continuation)
Definition Future.h:88
FFutureState()=default
void MarkComplete()
Definition Future.h:109
bool IsComplete() const
Definition Future.h:62
bool WaitFor(const FTimespan &Duration) const
Definition Future.h:74
Definition ScopeLock.h:141
Definition Atomic.h:538
Definition Future.h:224
bool WaitFor(const FTimespan &Duration) const
Definition Future.h:295
typename StateType::MutableResultType MutableResultType
Definition Future.h:229
ConstResultType Get() const UE_LIFETIMEBOUND
Definition Future.h:244
TFutureBase()=default
bool IsValid() const
Definition Future.h:267
TFutureBase(TSharedPtr< StateType > &&InState)
Definition Future.h:322
typename StateType::RvalueResultType RvalueResultType
Definition Future.h:231
bool WaitUntil(const FDateTime &Time) const
Definition Future.h:307
typename StateType::ConstResultType ConstResultType
Definition Future.h:230
const TSharedPtr< StateType > & GetState() const
Definition Future.h:336
bool IsReady() const
Definition Future.h:256
ConstResultType Get() const
Definition Future.h:239
auto Then(Func Continuation)
Definition Future.h:680
auto Next(Func Continuation)
Definition Future.h:701
void Wait() const
Definition Future.h:280
void Reset()
Definition Future.h:371
TFutureBase(const TSharedPtr< StateType > &InState)
Definition Future.h:326
Definition Future.h:146
~TFutureState()
Definition Future.h:157
typename TTypeCompatibleBytes< ResultType >::ConstGetType ConstResultType
Definition Future.h:149
TFutureState(TUniqueFunction< void()> &&CompletionCallback)
Definition Future.h:170
typename TTypeCompatibleBytes< ResultType >::MutableGetType MutableResultType
Definition Future.h:148
TFutureState()
Definition Future.h:153
typename TTypeCompatibleBytes< ResultType >::RvalueGetType RvalueResultType
Definition Future.h:150
MutableResultType GetResult()
Definition Future.h:182
ConstResultType GetResult() const
Definition Future.h:191
void EmplaceResult(ArgTypes &&... Args)
Definition Future.h:203
Definition Future.h:393
TFuture(const TFuture &)=delete
TSharedFuture< ResultType > Share()
Definition Future.h:452
TFuture & operator=(TFuture &&)=default
TFuture(TFuture &&)=default
MutableResultType GetMutable()
Definition Future.h:424
~TFuture()=default
TFuture & operator=(const TFuture &)=delete
MutableResultType GetMutable() UE_LIFETIMEBOUND
Definition Future.h:429
ResultType Consume()
Definition Future.h:441
TFuture()=default
Definition Future.h:541
TPromise()
Definition Future.h:550
const TSharedPtr< StateType > & GetState()
Definition Future.h:639
void SetValue()
Definition Future.h:613
TFuture< ResultType > GetFuture()
Definition Future.h:587
~TPromise()
Definition Future.h:572
TPromise(TPromise &&Other)=default
void SetValue(const SetType &Result)
Definition Future.h:603
TPromise(TUniqueFunction< void()> &&CompletionCallback)
Definition Future.h:560
TPromise & operator=(const TPromise &Other)=delete
void EmplaceValue(ArgTypes &&... Args)
Definition Future.h:628
void SetValue(SetType &&Result)
Definition Future.h:608
TPromise(const TPromise &Other)=delete
TPromise & operator=(TPromise &&Other)=default
Definition Future.h:490
ConstResultType Get() const
Definition Future.h:520
TSharedFuture()=default
TSharedFuture(TFuture< ResultType > &&Future)
Definition Future.h:510
Definition SharedPointer.h:692
Definition FunctionFwd.h:19
Definition Future.h:660
implementation
Definition PlayInEditorLoadingScope.h:8
Definition DateTime.h:76
static CORE_API FDateTime UtcNow()
Definition DateTime.cpp:980
Definition PooledSyncEvent.h:9
Definition Timespan.h:76
static FTimespan MaxValue()
Definition Timespan.h:686
Definition TypeCompatibleBytes.h:24
ElementType & GetUnchecked() &
Definition TypeCompatibleBytes.h:52
ElementType & MutableGetType
Definition TypeCompatibleBytes.h:47
const ElementType & ConstGetType
Definition TypeCompatibleBytes.h:48
void DestroyUnchecked()
Definition TypeCompatibleBytes.h:75
ElementType && RvalueGetType
Definition TypeCompatibleBytes.h:49
void EmplaceUnchecked(ArgTypes &&... Args)
Definition TypeCompatibleBytes.h:68
Definition Future.h:26
auto Requires(Type &Callable, int32 Val) -> decltype(Callable(Val))