Debian Codegraph @

liblomiri-app-launch/glib-thread.h

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 #pragma once
21
22 #include <future>
23 #include <mutex>
24 #include <thread>
25
26 #include <gio/gio.h>
27
28 namespace GLib
29 {
30
31 class ContextThread
32 {
33 std::thread _thread;
34 std::shared_ptr<GMainContext> _context;
35 std::shared_ptr<GMainLoop> _loop;
36 std::shared_ptr<GCancellable> _cancel;
37
38 std::function<void(void)> afterLoop_;
39 std::shared_ptr<std::once_flag> afterFlag_;
40
41 public:
42 ContextThread(const std::function<void()>& beforeLoop = [] {}, const std::function<void()>& afterLoop = [] {});
43 ~ContextThread();
44
45 void quit();
46 bool isCancelled();
47 std::shared_ptr<GCancellable> getCancellable();
48
49 guint executeOnThread(std::function<void()> work);
50 template <typename T>
51 auto executeOnThread(std::function<T()> work) -> T
52 {
53 if (std::this_thread::get_id() == _thread.get_id())
54 {
55 /* Don't block if we're on the same thread */
56 return work();
57 }
58
59 std::promise<T> promise;
60 std::function<void()> magicFunc = [&promise, &work]() {
61 try
62 {
63 promise.set_value(work());
64 }
65 catch (...)
66 {
67 promise.set_exception(std::current_exception());
68 }
69 };
70
71 executeOnThread(magicFunc);
72
73 auto future = promise.get_future();
74 future.wait();
75 return future.get();
76 }
77
78 guint timeout(const std::chrono::milliseconds& length, std::function<void()> work);
79 template <class Rep, class Period>
80 guint timeout(const std::chrono::duration<Rep, Period>& length, std::function<void()> work)
81 {
82 return timeout(std::chrono::duration_cast<std::chrono::milliseconds>(length), work);
83 }
84
85 guint timeoutSeconds(const std::chrono::seconds& length, std::function<void()> work);
86 template <class Rep, class Period>
87 guint timeoutSeconds(const std::chrono::duration<Rep, Period>& length, std::function<void()> work)
88 {
89 return timeoutSeconds(std::chrono::duration_cast<std::chrono::seconds>(length), work);
90 }
91
92 void removeSource(guint sourceid);
93
94 private:
95 guint simpleSource(std::function<GSource*()> srcBuilder, std::function<void()> work);
96 };
97 }