Re: [asio-users] async_read overwrites buffer even while the handler is running?
Brought to you by:
chris_kohlhoff
From: Igor R <boo...@gm...> - 2011-11-10 18:54:50
|
Hi, > yes, you sketched it right. Exactly this was happening in my case. > > I think, however, there is no such rule of thumb that async_read > operations should be scheduled from read handlers only, right? Well, I'd say it *is* rule of thumb, but not the "iron rule" :). I.e. you don't have to call async_xxx from the completion handler, but usually it would be the most safe and convenient way. If you take a look at the asio examples, in most of cases it's done this way there. Anyway, you have to ensure that only 1 async_read is in progress. In my code I do it in the following way: struct connection { // any attempt to async.read should be done through this function only // you can call it anytime with no worries activate_read() { if (!active_read_) { active_read_ = true; async_read_some(...); } } void read_handler(...) { active_read_ = false; // do things... if (some_condition()) activate_read(); } void other_func_requiring_to_read() { //... activate_read(); } }; In other words, I make a trivial state-machine, which enforces the above rule. > Since otherwise I would not be able pursue any protocol where one have > to read a response from the socket back as soon as you wrote something to it. > In such scenario cancel() of the parallel read/write operation might > be required, which is in other case not well portable (some troubles > with it in my other thread on the list). > Or there must be some kind of state-based implementation, to make sure > that you never have to cancel any operation (except when timeout, but > here a close() might be also ok). Actually, in the numerous clients and servers that I wrote with asio I reallly never had to cancel i/o operations (maybe only during connection closing process). HTH, Igor'. |