UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
RWSpinLock.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"
8
9#include <atomic>
10
11namespace UE
12{
13 // A read-write lock that doesn't put the thread into a WAIT state but instead repeatedly tries to acquire the lock.
14 // WARNING: Should be used only for very short locks.
15 // Use with `TRWScopeLock`, `TWriteScopeLock` or `TReadScopeLock`.
16 // The SizeType template type dictates the space taken by the spinlock but also its maximum number of possible concurrent readers (i.e. 254 for uint8, etc...).
17 // Read locks support recursion. Write locks don't support recursion even if coming from the same thread currently owning the write lock.
18 template <typename SizeType = uint32>
20 {
21 public:
22 static_assert(TNumericLimits<SizeType>::Min() >= 0, "Type must be unsigned");
24
25 TRWSpinLock() = default;
26
28 {
29 SizeType Expected = 0;
30 return Lock.compare_exchange_strong(Expected, TNumericLimits<SizeType>::Max(), std::memory_order_acquire, std::memory_order_relaxed);
31 }
32
33 void WriteLock()
34 {
35 while (!TryWriteLock())
36 {
37 // Reduce contention by doing a simple relaxed read to see if we have a chance of being able to lock.
38 while (Lock.load(std::memory_order_relaxed) != 0)
39 {
41 }
42 }
43 }
44
46 {
47 Lock.store(0, std::memory_order_release);
48 }
49
51 {
52 SizeType LocalValue = Lock.load(std::memory_order_relaxed);
53 // Check to make sure we don't already have a write lock or that we've not reached the limit of reader locks.
55 {
56 return false;
57 }
58
59 return Lock.compare_exchange_strong(LocalValue, LocalValue + 1, std::memory_order_acquire, std::memory_order_relaxed);
60 }
61
62 void ReadUnlock()
63 {
64 Lock.fetch_sub(1, std::memory_order_release);
65 }
66
67 void ReadLock()
68 {
69 while (!TryReadLock())
70 {
72 }
73 }
74
75 private:
76 std::atomic<SizeType> Lock = 0;
77 };
78
80}
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
Definition RWSpinLock.h:20
UE_NONCOPYABLE(TRWSpinLock)
TRWSpinLock()=default
bool TryWriteLock()
Definition RWSpinLock.h:27
void ReadUnlock()
Definition RWSpinLock.h:62
void WriteUnlock()
Definition RWSpinLock.h:45
void ReadLock()
Definition RWSpinLock.h:67
bool TryReadLock()
Definition RWSpinLock.h:50
void WriteLock()
Definition RWSpinLock.h:33
Definition AdvancedWidgetsModule.cpp:13
static void Yield()
Definition GenericPlatformProcess.h:950
Definition NumericLimits.h:41