forked from citizenfx/fivem
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeferredInitializer.h
More file actions
64 lines (51 loc) · 952 Bytes
/
DeferredInitializer.h
File metadata and controls
64 lines (51 loc) · 952 Bytes
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
#pragma once
struct DeferredInitializer
{
template<typename TFn>
inline static std::shared_ptr<DeferredInitializer> Create(TFn&& fn)
{
HANDLE event = CreateEventW(NULL, TRUE, FALSE, NULL);
struct Data
{
TFn fn;
HANDLE hEvent;
explicit Data(TFn&& fn, HANDLE hEvent)
: fn(std::move(fn)), hEvent(hEvent)
{
}
};
auto data = new Data(std::move(fn), event);
QueueUserWorkItem([](LPVOID arg)
{
auto data = reinterpret_cast<Data*>(arg);
data->fn();
SetEvent(data->hEvent);
delete data;
return DWORD(0);
}, data, 0);
return std::make_shared<DeferredInitializer>(event);
}
inline ~DeferredInitializer()
{
if (event)
{
CloseHandle(event);
event = NULL;
}
}
inline void Wait()
{
if (event)
{
WaitForSingleObject(event, INFINITE);
CloseHandle(event);
event = NULL;
}
}
explicit DeferredInitializer(HANDLE event)
: event(event)
{
}
private:
HANDLE event;
};