Reputation: 153
After reading these...
Cancelling boost asio deadline timer safely
Atomically cancel asio asynchronious timer from another thread
...I'd like to try and get clarification on an aspect of usage.
Per the first referenced question, cancelling a timer after it has expired but before its handler has run doesn't work. The handler for such an "in-flight" timer still runs normally.
This brings up a lifecycle question... A common usage pattern is for a timer to be a member of a class, and for its expiration handler to reference that parent class. The parent class can cancel the timer from its destructor, but there would seem to be a crash exposure under the scenario above since both the timer and parent class no longer exist when the handler runs.
If this is indeed the case, how can it be resolved? We could capture a std::weak_ptr to the parent class in the handler and check it before proceeding, but not every parent class may have its life-cycle managed via std::shared_ptr.
Upvotes: 0
Views: 252
Reputation: 2569
Below is my observation based on Net.ts, but not ASIO-- I believe there wouldn't be any fundamental change between them.
when we cancel the timer-- regardless of its expiration, its handlers or pending_waiter will run, and it looks like, they all run with their error_code
set to
op->ec_ = std::experimental::net::v1::error::operation_aborted;
So, to my understanding, your second question is: what if I have a timer object inside a class, and for some reasons the destructor of an object belongs to that class runs and cancels out the timer( ? )
In asynchronous programming (specifically the one that established using callbacks), the error_code
argument that gets passed to your handler plays a major role.
So, in your scenario, I believe you could get over the supposed "crash exposure" using
if(ec == std::experimental::net::v1::error::operation_aborted)
LOG(....) or return;
Edit: if your ask is how can we manage the life-cycle of an object, then I can say there are multiple ways to do it, but the point I want to bring via my remark is, the timer object whenever cancelled, it informs you via ec
that it has got cancelled and decide your next move based on that.
Upvotes: 0