UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
Mutex.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#include "Async/LockTags.h"
6#include "CoreTypes.h"
7#include <atomic>
8
9#define UE_API CORE_API
10
11namespace UE
12{
13
17class FMutex final
18{
19public:
20 constexpr FMutex() = default;
21
23 inline explicit FMutex(FAcquireLock)
24 : State(IsLockedFlag)
25 {
26 }
27
28 FMutex(const FMutex&) = delete;
29 FMutex& operator=(const FMutex&) = delete;
30
31 [[nodiscard]] inline bool IsLocked() const
32 {
33 return !!(State.load(std::memory_order_relaxed) & IsLockedFlag);
34 }
35
36 [[nodiscard]] inline bool TryLock()
37 {
38 uint8 Expected = State.load(std::memory_order_relaxed);
39 return !(Expected & IsLockedFlag) &&
40 State.compare_exchange_strong(Expected, Expected | IsLockedFlag, std::memory_order_acquire, std::memory_order_relaxed);
41 }
42
43 inline void Lock()
44 {
45 uint8 Expected = 0;
46 if (LIKELY(State.compare_exchange_weak(Expected, IsLockedFlag, std::memory_order_acquire, std::memory_order_relaxed)))
47 {
48 return;
49 }
50 LockSlow();
51 }
52
53 inline void Unlock()
54 {
55 // Unlock immediately to allow other threads to acquire the lock while this thread looks for a thread to wake.
56 const uint8 LastState = State.fetch_sub(IsLockedFlag, std::memory_order_release);
57 if (LIKELY(!(LastState & MayHaveWaitingLockFlag)))
58 {
59 return;
60 }
61 WakeWaitingThread();
62 }
63
64private:
65 UE_API void LockSlow();
66 UE_API void WakeWaitingThread();
67
68 struct FParams;
69
70 static constexpr uint8 IsLockedFlag = 1 << 0;
71 static constexpr uint8 MayHaveWaitingLockFlag = 1 << 1;
72
73 std::atomic<uint8> State = 0;
74};
75
76} // UE
77
78#undef UE_API
#define LIKELY(x)
Definition CityHash.cpp:107
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
#define UE_API
Definition SColorGradingComponentViewer.h:12
uint8_t uint8
Definition binka_ue_file_header.h:8
Definition Mutex.h:18
FMutex(FAcquireLock)
Definition Mutex.h:23
bool IsLocked() const
Definition Mutex.h:31
void Lock()
Definition Mutex.h:43
FMutex & operator=(const FMutex &)=delete
void Unlock()
Definition Mutex.h:53
constexpr FMutex()=default
bool TryLock()
Definition Mutex.h:36
FMutex(const FMutex &)=delete
Definition AdvancedWidgetsModule.cpp:13
Definition LockTags.h:9