-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCore.Thread.h
More file actions
89 lines (74 loc) · 1.6 KB
/
Copy pathCore.Thread.h
File metadata and controls
89 lines (74 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once
#include <windows.h>
#include <process.h>
#include <functional>
#include <atomic>
#include <cassert>
class Thread
{
public:
using TaskFunc = std::function<void()>;
Thread() = default;
~Thread()
{
Stop();
}
bool Start(TaskFunc task)
{
assert(!m_threadHandle && "Thread: 이미 시작된 스레드를 다시 시작할 수 없다");
if (!task) return false;
m_task = std::move(task);
m_stopRequested.store(false);
m_threadHandle = reinterpret_cast<HANDLE>(
_beginthreadex(nullptr, 0, &ThreadEntry, this, 0, &m_threadId)
);
return m_threadHandle != nullptr;
}
void Stop()
{
RequestStop();
Join();
}
void RequestStop()
{
m_stopRequested.store(true, std::memory_order_release);
}
void Join()
{
if (m_threadHandle)
{
WaitForSingleObject(m_threadHandle, INFINITE);
CloseHandle(m_threadHandle);
m_threadHandle = nullptr;
}
}
void SetAffinity(DWORD_PTR mask)
{
if (m_threadHandle)
SetThreadAffinityMask(m_threadHandle, mask);
}
void SetPriority(int priority)
{
if (m_threadHandle)
SetThreadPriority(m_threadHandle, priority);
}
bool IsStopRequested() const
{
return m_stopRequested.load(std::memory_order_acquire);
}
DWORD GetThreadId() const { return m_threadId; }
HANDLE GetThreadHandle() const { return m_threadHandle; }
private:
static unsigned __stdcall ThreadEntry(void* arg)
{
Thread* thread = static_cast<Thread*>(arg);
if (thread && thread->m_task)
thread->m_task();
return 0;
}
private:
HANDLE m_threadHandle{ nullptr };
uint32_t m_threadId = 0;
TaskFunc m_task;
std::atomic_bool m_stopRequested{ false };
};