LkEngine 0.1.2
 
Loading...
Searching...
No Matches
Thread.h
1#pragma once
2
3#include <optional>
4
6
7namespace LkEngine {
8
9 using FThreadHandle = uint64_t;
10
16 class IThread
17 {
18 public:
19 virtual ~IThread() = default;
20
21 virtual void Run() = 0;
22 virtual FThreadHandle GetHandle() const = 0;
23 virtual bool IsRunning() const = 0;
24 };
25
31 template<typename TPlatformType>
32 class LThread : public IThread
33 {
34 public:
35 LThread() = default;
36 template<typename TCallable, typename ...TArgs>
37 LThread(TCallable&& Func, TArgs&&... Args)
38 {
39 Task = [Func = std::forward<TCallable>(Func), ...Args = std::forward<TArgs>(Args)]() mutable
40 {
41 std::invoke(Func, std::move(Args)...);
42 };
43 }
44
45 virtual ~LThread() = default;
46
51 template<typename TCallable, typename ...TArgs>
52 void Setup(TCallable&& Func, TArgs&&... Args)
53 {
54 Task = [Func = std::forward<TCallable>(Func), ...Args = std::forward<TArgs>(Args)]() mutable
55 {
56 std::invoke(Func, std::move(Args)...);
57 };
58 }
59
60 FORCEINLINE void Run()
61 {
62 LK_CORE_DEBUG_TAG("LThread", "Invoking Run");
63 if (WorkerThread.joinable())
64 {
65 LK_CORE_ERROR_TAG("LThread", "Thread is already running");
66 assert(false);
67 }
68
69 if (Task && Task.has_value())
70 {
71 WorkerThread = std::thread([this]
72 {
73 bIsRunning = true;
74
75 if (Task)
76 {
77 (*Task)();
78 }
79
80 bIsRunning = false;
81 });
82 }
83 }
84
88 FORCEINLINE FThreadHandle GetHandle() const { return Handle; }
89
93 FORCEINLINE bool IsRunning() const { return bIsRunning; }
94
99 template <typename TRep, typename TPeriod>
100 static void Sleep(const std::chrono::duration<TRep, TPeriod> Duration)
101 {
102 std::this_thread::sleep_for(Duration);
103 }
104
105 protected:
106 FThreadHandle Handle = 0;
107
108 std::thread WorkerThread;
109 std::optional<std::function<void()>> Task;
110
111 bool bIsRunning = false;
112 };
113
115 {
116 bool bIsRunning = true;
117 std::queue<std::function<void()>> CommandQueue{};
118 };
119
120}
Core header.
Definition Thread.h:17
Definition Thread.h:33
FORCEINLINE bool IsRunning() const
Check if the thread is running.
Definition Thread.h:93
static void Sleep(const std::chrono::duration< TRep, TPeriod > Duration)
Sleep for a duration, inhibiting thread execution. Uses std::chrono.
Definition Thread.h:100
FORCEINLINE FThreadHandle GetHandle() const
Get the thread handle.
Definition Thread.h:88
void Setup(TCallable &&Func, TArgs &&... Args)
Setup thread. Used whenever the thread function hasn't been passed in the constructor.
Definition Thread.h:52
Definition Asset.h:11
Definition Thread.h:115