Re: [asio-users] Implementing asynchronous completion tokens
Brought to you by:
chris_kohlhoff
From: Christopher K. <ch...@ko...> - 2009-07-27 08:12:57
|
On Fri, 24 Jul 2009 12:40 +0200, "Rutger ter Borg" <ru...@te...> wrote: > My typical use case is that an asynchronous operation depends on a > couple of asynchronous operations in between (e.g., async send out the > request carrying the token over a socket, async process a result, > etc.). If an incoming message contains the result for such an handler; > pick it up and post the handler to the io_service. > > Currently I am using a table-based implementation. I was wondering > whether this could be done more robust/efficient through some of the > more hidden facilities of asio. E.g., facilities for storing unbound > handlers. You can also use a deadline_timer to store unbound handlers. Imagine your message table looks something like: struct waiting_handler { ... deadline_timer t; message m; } waiting_handlers[N]; and your handlers have a signature like: void handle_message(message m); You store your handler like so: template <typename Handler> struct wrapped_handler { int id; Handler h; void operator()(const error_code&) { h(waiting_handlers[id].m); } }; ... wrapped_handler<Handler> wh = { 42, h }; waiting_handlers.expires_at(boost::posix_time::pos_infin); waiting_handlers[42].t.async_wait(wh); And when you receive a message for a given message id, you use: waiting_handlers[id].m = m; waiting_handlers[id].t.expires_at(boost::posix_time::neg_infin); Whenever a timer's expiry is modified, any waiting handlers are queued for invocation. Cheers, Chris |