-
Notifications
You must be signed in to change notification settings - Fork 0
/
Actor.cpp
116 lines (95 loc) · 2.18 KB
/
Actor.cpp
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "Actor.h"
#include <thread>
#include "EventSource.h"
namespace {
struct GlibUnref {
void operator() (GMainContext* context)
{ g_main_context_unref(context); }
void operator() (GMainLoop* loop)
{ g_main_loop_unref(loop); }
void operator() (GAsyncQueue* queue)
{ g_async_queue_unref(queue); }
};
typedef
std::unique_ptr<
GMainContext,
GlibUnref> GMainContextPtr;
typedef
std::unique_ptr<
GMainLoop,
GlibUnref> GMainLoopPtr;
typedef
std::unique_ptr<
GAsyncQueue,
GlibUnref> GAsyncQueuePtr;
struct Action {
Actor::Action action;
};
void OnEvent(GAsyncQueue* queue)
{
while(gpointer item = g_async_queue_try_pop(queue)) {
std::unique_ptr<Action>(static_cast<Action*>(item))->action();
}
}
void ActorMain(
GMainContext* mainContext,
GMainLoop* mainLoop,
GAsyncQueue* queue,
EventSource* notifier)
{
g_main_context_push_thread_default(mainContext);
notifier->subscribe(std::bind(&OnEvent, queue));
g_main_loop_run(mainLoop);
}
}
struct Actor::Private {
Private();
void postQuit();
GMainContextPtr mainContextPtr;
GMainLoopPtr mainLoopPtr;
GAsyncQueuePtr queuePtr;
EventSource notifier;
std::thread actorThread;
};
Actor::Private::Private() :
mainContextPtr(g_main_context_new()),
mainLoopPtr(g_main_loop_new(mainContextPtr.get(), FALSE)),
queuePtr(g_async_queue_new()),
notifier(mainContextPtr.get()),
actorThread(
ActorMain,
mainContextPtr.get(),
mainLoopPtr.get(),
queuePtr.get(),
¬ifier)
{
}
void Actor::Private::postQuit()
{
GMainLoop* loop = mainLoopPtr.get();
g_async_queue_push(
queuePtr.get(),
new Action {
[loop] () {
g_main_loop_quit(loop);
}
});
}
Actor::Actor() :
_p(std::make_unique<Private>())
{
}
Actor::~Actor()
{
if(_p->actorThread.joinable()) {
_p->postQuit();
_p->actorThread.join();
}
}
void Actor::postAction(const Action& action)
{
g_async_queue_push(
_p->queuePtr.get(),
new ::Action { action });
_p->notifier.postEvent();
}