|
|
Subscribe / Log in / New account

Error in code sample?

Error in code sample?

Posted Sep 28, 2025 11:32 UTC (Sun) by excors (subscriber, #95769)
In reply to: Error in code sample? by Nikratio
Parent article: Canceling asynchronous Rust

I think the Ok(Err) case doesn't count as cancellation, it's just normal synchronous error handling. Cancellation is specifically when a Future is dropped before it has completed (i.e. before its `poll` function has returned Poll::Ready(_)). In this case tx.reserve() constructed the Future, and its `poll` has returned Poll::Ready(Err(_)), so the Future has completed and there is no cancellation.

In contrast, `timeout` constructs a new Future that wraps the original Future, and (on timeout) the outer Future completes but the inner Future is dropped (cancelled). And any resources owned by the inner Future (e.g. `msg`, in the original `timeout(tx.send(msg))` example) are dropped too, which is the issue being solved by the later example.

In practice the code should have some better error handling for Ok(Err) that isn't simply `return;`, but maybe e.g. it's going to reset the whole channel and the old message is redundant so it's okay to drop it; that will depend on context and is outside the scope of this example.

I think in general you shouldn't move the next_message() call in between reserve() and send(), because next_message() might be expensive and perhaps async itself; you might hold the reservation for a very long time, wasting the channel's capacity. You'd need a different way to handle `msg` in the error case, if not simply dropping it.


to post comments


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds