Re: [asio-users] structured programming with asio
Brought to you by:
chris_kohlhoff
From: Stephan M. <sm...@gm...> - 2007-03-29 15:20:29
|
Am Donnerstag, 29. M=E4rz 2007 16:01:02 schrieb Christopher Kohlhoff: > Can you illustrate this with a bit of pseudocode? I think it may be > possible to do something similar using multiple io_service objects, but > I'd like to see how you think the deadline_timer solution would work > before I can say for sure. Hi Chris, I managed to get it to work as I described. I'm not so good in Pseudocode b= ut=20 I'll try to simplify on my current working example of an async DNS query=20 inside an object: class DNS: public boost::enable_shared_from_this<DNS> { public: typedef boost::shared_ptr<DNS> pointer; static pointer create(asio::io_service &iosrv) { return pointer(new DNS(iosrv)); } asio::deadline_timer &getTimer(void) {return _timer;}; void do_query(const std::string &ip) throw () { asio::ip::tcp::resolver::query query(querystring, ""); _resolver.async_resolve(query, boost::bind(&DNS::handleQuery, shared_from_this(), asio::placeholders::error, asio::placeholders::iterator)); } void handleQuery(const asio::error& err, asio::ip::tcp::resolver::itera= tor=20 it) { // store the result to be accessed from the object later _timer.expires_from_now(boost::posix_time::seconds(0)); } private: =20 DNS(asio::io_service &iosrv) : _resolver(iosrv), _timer(iosrv) {}; asio::ip::tcp::resolver _resolver; asio::deadline_timer _timer; } class UsingClient { public: UsingClient : _dns(DNS::create(_iosrv)) {}; =20 someCallbackStartingTheQuery() { _dns->do_query(domain); // tell the _dns to start the query // when finished, this timer will be our trigger _dns->getTimer().async_wait( boost::bind(&UsingClient::someOtherCallbackFinishing, shared_from_this(), asio::placeholders::error)); } someOtherCallbackFinishing() { // retrieve the result from _dns object and continue } private: boost::shared_ptr<DNS> _dns; } Looking a bit complicated, but the key thing is, it works.=20 With -D_GLIBCXX_DEBUG switched off only though, due to the problem I report= ed=20 yesterday. Anyway, it did not work when UsingClient instantiates the DNS object direct= ly=20 rather than using the shared ptr for unknown reason. I always got a=20 bad_weak_ptr exception when doing the async_wait on the timer. Apparently t= he=20 object is being moved or destroyed on the way or something. Couldn't figure= =20 it out, so I'm using the apparently unnecessary shared_ptr to keep at least= a=20 reference count of one to the DNS object. My problem is: All that looks kinda weird and complicated for a seemingly=20 simple thing so I thought there might be a more simple and obvious approach= =20 I'm missing here. I hope I could clearify this a bit. Greetings... Stephan |