Debian Codegraph @

examples/gio-async.cpp

raw symbols SCIP
1 #define GI_INLINE 1
2 #include <gio/gio.hpp>
3
4 #include <iostream>
5
6 #if GI_CONFIG_EXCEPTIONS
7 #include <boost/fiber/all.hpp>
8
9 namespace GLib = gi::repository::GLib;
10 namespace GObject_ = gi::repository::GObject;
11 namespace Gio = gi::repository::Gio;
12
13 class context_scheduler : public boost::fibers::algo::round_robin
14 {
15 typedef context_scheduler self;
16 typedef boost::fibers::algo::round_robin super;
17
18 struct src : GSource
19 {
20 self *scheduler;
21 };
22
23 GSourceFuncs funcs{};
24 GLib::MainContext ctx_;
25 src *source_;
26 boost::fibers::condition_variable cond_;
27 boost::fibers::mutex mtx_;
28 using clock_type = std::chrono::steady_clock;
29 bool dispatching_ = false;
30
31 static gboolean src_dispatch(
32 GSource *source, GSourceFunc /*callback*/, gpointer /*user_data*/)
33 {
34 auto s = (src *)(source);
35 auto sched = s->scheduler;
36 // wait here to give (other) fibers a chance
37 sched->dispatching_ = true;
38 std::unique_lock<boost::fibers::mutex> lk(sched->mtx_);
39 sched->cond_.wait(lk);
40 sched->dispatching_ = false;
41 // all available work has been done while we were waiting above
42 // no need to dispatch again until new work
43 // which we accept as of now (due to mainloop activity)
44 return G_SOURCE_CONTINUE;
45 }
46
47 public:
48 context_scheduler(GLib::MainContext ctx) : ctx_(ctx)
49 {
50 // this is a bit too much for bindings, so handle the raw C way
51 funcs.dispatch = src_dispatch;
52 auto s = g_source_new(&funcs, sizeof(src));
53 source_ = (src *)(s);
54 source_->scheduler = this;
55 g_source_attach(s, ctx.gobj_());
56 }
57
58 ~context_scheduler()
59 {
60 g_source_destroy(source_);
61 g_source_unref(source_);
62 }
63
64 void awakened(boost::fibers::context *t) noexcept override
65 {
66 // delegate first
67 super::awakened(t);
68 // arrange for dispatch of work
69 // discard awake of source dispatch
70 if (!dispatching_)
71 g_source_set_ready_time(source_, 0);
72 }
73
74 void suspend_until(
75 std::chrono::steady_clock::time_point const &abs_time) noexcept override
76 {
77 // release dispatch
78 // should only end up here while dispatching in source
79 // (rather than inadvertently trying to block main loop,
80 // which would then lead to busy loop)
81 if (dispatching_) {
82 // derive time of subsequent dispatch
83 if (clock_type::time_point::max() != abs_time) {
84 auto to = abs_time - std::chrono::steady_clock::now();
85 int ms =
86 std::chrono::duration_cast<std::chrono::milliseconds>(to).count();
87 ms = std::max(ms, 0);
88 g_source_set_ready_time(source_, g_get_monotonic_time() + ms);
89 } else {
90 g_source_set_ready_time(source_, -1);
91 }
92 // release source dispatching
93 cond_.notify_one();
94 } else {
95 // suspend is requested, so there is nothing to do for a while
96 // so in particular the main fiber is then also blocked (e.g. some sleep)
97 // such main loop blocking is also/still not allowed
98 // (if such is active)
99 g_assert(g_main_depth() == 0);
100 // no running loop (so also no dispatch)
101 // so delegate to the usual scheduling
102 // (which will really block the hard way, rather than poll)
103 super::suspend_until(abs_time);
104 }
105 }
106
107 // might be called from a different thread
108 void notify() noexcept override
109 {
110 // discard our own notify above to resume source dispatch
111 if (dispatching_)
112 return;
113 ctx_.wakeup();
114 }
115 };
116
117 class async_future
118 {
119 boost::fibers::promise<Gio::AsyncResult> p_;
120 boost::fibers::future<Gio::AsyncResult> f_;
121 Gio::Cancellable cancel_;
122 GLib::Source timeout_;
123
124 public:
125 ~async_future()
126 {
127 if (timeout_)
128 timeout_.destroy();
129 }
130
131 operator Gio::AsyncReadyCallback()
132 {
133 // prepare a new promise
134 p_ = decltype(p_)();
135 f_ = p_.get_future();
136 return [&](GObject_::Object, Gio::AsyncResult result) {
137 // clear state for subsequent re-use if needed
138 if (cancel_ && cancel_.is_cancelled())
139 cancel_ = nullptr;
140 p_.set_value(result);
141 };
142 }
143
144 Gio::AsyncResult get() { return f_.get(); }
145
146 Gio::Cancellable cancellable()
147 {
148 if (!cancel_)
149 cancel_ = Gio::Cancellable::new_();
150 return cancel_;
151 }
152
153 Gio::Cancellable timeout(const std::chrono::milliseconds &to)
154 {
155 auto cancel = cancellable();
156 if (to.count() > 0) {
157 timeout_ = GLib::timeout_source_new(to.count());
158 auto do_timeout = [cancel]() mutable {
159 cancel.cancel();
160 return GLib::SOURCE_REMOVE_;
161 };
162 timeout_.set_callback<GLib::SourceFunc>(do_timeout);
163 timeout_.attach(GLib::MainContext::get_thread_default());
164 }
165 return cancel_;
166 }
167 };
168
169 static void
170 async_client(int port, int id, int &count)
171 {
172 async_future w;
173
174 auto dest = Gio::NetworkAddress::new_loopback(port);
175
176 std::string sid = "client ";
177 sid += std::to_string(id);
178
179 // connect a client
180 std::cout << sid << ": connect" << std::endl;
181 auto client = Gio::SocketClient::new_();
182 client.connect_async(dest, w);
183 auto conn = gi::expect(client.connect_finish(w.get()));
184
185 // say something
186 auto os = conn.get_output_stream();
187 std::cout << sid << ": send: " << sid << std::endl;
188 os.write_all_async(
189 (guint8 *)sid.data(), sid.size(), GLib::PRIORITY_DEFAULT_, w);
190 os.write_all_finish(w.get(), (gsize *)nullptr);
191
192 // now hear what the other side has to say
193 std::cout << sid << ": receive" << std::endl;
194 auto is = conn.get_input_stream();
195 while (1) {
196 guint8 data[1024];
197 is.read_async(data, sizeof(data), GLib::PRIORITY_DEFAULT_, w);
198 auto size = gi::expect(is.read_finish(w.get()));
199 if (!size)
200 break;
201 std::string msg(data, data + size);
202 std::cout << sid << ": got data: " << msg << std::endl;
203 }
204
205 std::cout << sid << ": closing down" << std::endl;
206 --count;
207 }
208
209 static void
210 async_handle_client(Gio::SocketConnection conn)
211 {
212 async_future w;
213
214 // say hello
215 auto os = conn.get_output_stream();
216 std::string msg = "hello ";
217 os.write_all_async(
218 (guint8 *)msg.data(), msg.size(), GLib::PRIORITY_DEFAULT_, w);
219 os.write_all_finish(w.get(), (gsize *)nullptr);
220
221 // now echo what the other side has to say
222 auto is = conn.get_input_stream();
223 while (1) {
224 guint8 data[1024];
225 // give up if timeout
226 GLib::Error error;
227 is.read_async(data, sizeof(data), GLib::PRIORITY_DEFAULT_,
228 w.timeout(std::chrono::milliseconds(200)), w);
229 auto size = gi::expect(is.read_finish(w.get(), &error));
230 if (error) {
231 if (error.matches(G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
232 break;
233 } else {
234 throw error;
235 }
236 }
237 std::string msg(data, data + size);
238 std::cout << "server: got data: " << msg << std::endl;
239 os.write_all_async(data, size, GLib::PRIORITY_DEFAULT_, w);
240 os.write_all_finish(w.get(), (gsize *)nullptr);
241 }
242
243 std::cout << "server: closing down client" << std::endl;
244 }
245
246 static void
247 async_server(int clients, int &port)
248 {
249 async_future w;
250
251 auto listener = Gio::SocketListener::new_();
252 port = gi::expect(listener.add_any_inet_port());
253
254 int count = 0;
255 while (count < clients) {
256 // accept clients
257 std::cout << "server: accepting" << std::endl;
258 listener.accept_async(w);
259 auto conn = gi::expect(
260 listener.accept_finish(w.get(), (GObject_::Object *)nullptr));
261
262 // spawn client handler
263 std::cout << "server: new connection" << std::endl;
264 boost::fibers::fiber c(async_handle_client, conn);
265 c.detach();
266 ++count;
267 }
268
269 // wait a bit and shutdown
270 // wait long enough to test the out-of-loop join below
271 boost::this_fiber::sleep_for(std::chrono::milliseconds(1000));
272 std::cout << "server: shutdown" << std::endl;
273 }
274
275 static void
276 async_demo(GLib::MainLoop loop, int clients)
277 {
278 // run server
279 // dispatch at once to obtain port
280 int port = 0;
281 boost::fibers::fiber server(
282 boost::fibers::launch::dispatch, async_server, clients, std::ref(port));
283
284 // make clients
285 int count = 0;
286 for (int i = 0; i < clients; ++i) {
287 ++count;
288 auto c = boost::fibers::fiber(async_client, port, i, std::ref(count));
289 c.detach();
290 }
291
292 // plain-and-simple; poll regularly and quit when all clients done
293 auto check = [&]() {
294 if (!count)
295 loop.quit();
296 return G_SOURCE_CONTINUE;
297 };
298 GLib::timeout_add(100, check);
299
300 std::cout << "running loop" << std::endl;
301 loop.run();
302 std::cout << "ending loop" << std::endl;
303
304 server.join();
305 }
306
307 int
308 main(int argc, char **argv)
309 {
310 GLib::MainLoop loop = GLib::MainLoop::new_();
311 auto ctx = GLib::MainContext::default_();
312 boost::fibers::use_scheduling_algorithm<context_scheduler>(ctx);
313
314 { // basic fiber demo
315 int count = 0;
316 auto work = [&](const std::string &msg) {
317 std::cout << msg << std::endl;
318 ++count;
319 };
320 auto quit = [&](int limit, const std::chrono::milliseconds &d) {
321 while (count < limit)
322 boost::this_fiber::sleep_for(d);
323 loop.quit();
324 };
325 boost::fibers::fiber f1(work, "fiber 1");
326 boost::fibers::fiber f2(work, "fiber 2");
327 boost::fibers::fiber q(quit, 2, std::chrono::milliseconds(100));
328
329 loop.run();
330
331 f1.join();
332 f2.join();
333 q.join();
334 }
335
336 // now an optional async GIO demo
337 int clients = argc > 1 ? std::stoi(argv[1]) : 0;
338 std::cout << clients << " clients" << std::endl;
339 if (clients > 0)
340 async_demo(loop, clients);
341 }
342
343 #else
344 int
345 main(int argc, char **argv)
346 {
347 (void)argc;
348 (void)argv;
349
350 std::cerr << "boost::fibers needs exceptions";
351 }
352
353 #endif