Debian Codegraph @

liblomiri-app-launch/glib-thread.cpp

raw
1 /*
2 * Copyright © 2015 Canonical Ltd.
3 *
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 3, as published
6 * by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranties of
10 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 * PURPOSE. See the GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Authors:
17 * Ted Gould <[email protected]>
18 */
19
20 #include "glib-thread.h"
21
22 #include <lomiri/util/GlibMemory.h>
23
24 using namespace lomiri::util;
25
26 namespace GLib
27 {
28
29 ContextThread::ContextThread(const std::function<void()>& beforeLoop, const std::function<void()>& afterLoop)
30 {
31 _cancel = std::shared_ptr<GCancellable>(g_cancellable_new(), [](GCancellable* cancel) {
32 if (cancel != nullptr)
33 {
34 g_cancellable_cancel(cancel);
35 g_object_unref(cancel);
36 }
37 });
38 std::promise<std::pair<std::shared_ptr<GMainContext>, std::shared_ptr<GMainLoop>>> context_promise;
39
40 /* NOTE: We copy afterLoop but reference beforeLoop. We're blocking so we
41 know that beforeLoop will stay valid long enough, but we can't say the
42 same for afterLoop */
43 afterLoop_ = afterLoop;
44 afterFlag_ = std::make_shared<std::once_flag>();
45
46 _thread = std::thread([&context_promise, &beforeLoop, this]() {
47 /* Build up the context and loop for the async events and a place
48 for GDBus to send its events back to */
49 auto context = share_glib(g_main_context_new());
50 auto loop = share_glib(g_main_loop_new(context.get(), FALSE));
51
52 g_main_context_push_thread_default(context.get());
53
54 beforeLoop();
55
56 /* Free's the constructor to continue */
57 context_promise.set_value(std::make_pair(context, loop));
58
59 if (!g_cancellable_is_cancelled(_cancel.get()))
60 {
61 g_main_loop_run(loop.get());
62 }
63
64 std::call_once(*afterFlag_, afterLoop_);
65
66 /*
67 * Drain the event sources. Some event sources hold a reference to the
68 * main context. If we don't drain them, we might leak the source and
69 * whatever resource it holds (i.e. a GDBusConnection). This is primarily
70 * to please the test, but I think it has some real benefit.
71 */
72 while (g_main_context_iteration(context.get(), /* may_block */ FALSE)) {}
73 });
74
75 /* We need to have the context and the mainloop ready before
76 other functions on this object can work properly. So we wait
77 for them and set them on this thread. */
78 auto context_future = context_promise.get_future();
79 context_future.wait();
80 auto context_value = context_future.get();
81
82 _context = context_value.first;
83 _loop = context_value.second;
84
85 if (!_context || !_loop)
86 {
87 throw std::runtime_error("Unable to create GLib Thread");
88 }
89 }
90
91 ContextThread::~ContextThread()
92 {
93 quit();
94 }
95
96 void ContextThread::quit()
97 {
98 g_cancellable_cancel(_cancel.get()); /* Force the cancellation on ongoing tasks */
99 if (_loop)
100 {
101 g_main_loop_quit(_loop.get()); /* Quit the loop */
102 }
103
104 /* Joining here because we want to ensure that the final afterLoop()
105 function is run before returning */
106 if (_thread.joinable())
107 {
108 if (std::this_thread::get_id() != _thread.get_id())
109 {
110 _thread.join();
111 }
112 else
113 {
114 std::call_once(*afterFlag_, afterLoop_);
115 _thread.detach();
116 }
117 }
118 }
119
120 bool ContextThread::isCancelled()
121 {
122 return g_cancellable_is_cancelled(_cancel.get()) == TRUE;
123 }
124
125 std::shared_ptr<GCancellable> ContextThread::getCancellable()
126 {
127 return _cancel;
128 }
129
130 guint ContextThread::simpleSource(std::function<GSource*()> srcBuilder, std::function<void()> work)
131 {
132 if (isCancelled())
133 {
134 throw std::runtime_error("Trying to execute work on a GLib thread that is shutting down.");
135 }
136
137 /* Copy the work so that we can reuse it */
138 /* Lifecycle is handled with the source pointer when we attach
139 it to the context. */
140 auto heapWork = new std::function<void()>(work);
141
142 auto source = unique_glib(srcBuilder());
143 g_source_set_callback(source.get(),
144 [](gpointer data) {
145 auto heapWork = static_cast<std::function<void()>*>(data);
146 (*heapWork)();
147 return G_SOURCE_REMOVE;
148 },
149 heapWork,
150 [](gpointer data) {
151 auto heapWork = static_cast<std::function<void()>*>(data);
152 delete heapWork;
153 });
154
155 return g_source_attach(source.get(), _context.get());
156 }
157
158 guint ContextThread::executeOnThread(std::function<void()> work)
159 {
160 return simpleSource(g_idle_source_new, work);
161 }
162
163 guint ContextThread::timeout(const std::chrono::milliseconds& length, std::function<void()> work)
164 {
165 return simpleSource([length]() { return g_timeout_source_new(length.count()); }, work);
166 }
167
168 guint ContextThread::timeoutSeconds(const std::chrono::seconds& length, std::function<void()> work)
169 {
170 return simpleSource([length]() { return g_timeout_source_new_seconds(length.count()); }, work);
171 }
172
173 void ContextThread::removeSource(guint sourceid)
174 {
175 auto source = g_main_context_find_source_by_id(_context.get(), sourceid);
176 if (source == nullptr)
177 {
178 return;
179 }
180
181 g_source_destroy(source);
182 }
183
184 } // ns GLib