tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
26.59k stars 2.45k forks source link

6566 - Add 'run_until_cancelled' to 'tokio_util::sync::CancellationToken' #6618

Closed tglane closed 3 months ago

tglane commented 3 months ago

Motivation

Citing from #6566:

Give how (seemingly) often a tokio_util::sync::CancellationToken gets used as follows: tokio::select! { _ = token.cancelled() => { / something / } other => other_future => { / something else / } } I propose adding a method to CancellationToken that takes a Future, runs it to completion, and returns its output — unless the token is cancelled before the future completes, in which case the future is dropped. I feel the best type for the result of this composed future would be an Option, with None indicating cancellation.

Solution

I added the described function to tokio_util::sync::CancellationToken and added a test case to the loom tests. I also had to add the macros feature of Tokio to get access to the select! macro. I thought about using select! provided by futures_util but that would require WaitForCancellationFuture to implement FusedFuture so I had to stick with the tokio one. But maybe this is a not worthy trade off just for a convenience function?

This would close #6566