-
I'm currently building a system service that runs several never-ending tasks concurrently. It is important that when a single task fails, the error is bubbled up to the caller (and again bubbled up to the main function of the program). When I implement this concurrently with Tokio's
However, as soon as I try to run things in parallel I run into problems. According to the documentation of
But this poses two problems. First I get a type error I'm not sure I entirely understand.
If I match the result and simply discard it as I've been playing with this for some time and searched through documentation and examples, but thus far I haven't figured out the correct approach here. To stop the remaining tasks it seems I could use Abortable from the Could someone point me in the right direction here? How do I implement this correctly using Tokio? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Okay so first, the error
is due to this line:
The type of As for cancellation of tasks, first not that As for cancelling tasks, you can use a broadcast channel combined with tokio::select! {
_ = do_the_stuff() => {},
_ = broadcast.recv() => {},
} |
Beta Was this translation helpful? Give feedback.
-
@Darksonn Thank you for clarifying. You put me on the right track.
I still needed to flatten the nested Result I had due to the use of For posterity, this spawns a set of never-ending tasks not merely concurrently but also in parallel. Tasks return
|
Beta Was this translation helpful? Give feedback.
Okay so first, the error
is due to this line:
The type of
e
here is not aBox<dyn Error>
, so the return fails. You can doreturn Err(e.into());
to convert the error to a box.As for cancellation of tasks, first not that
tokio::spawn
wraps the thing in aResult
in case the spawned task panics, so if the tasks also returnResult
s, you will want some sort of flatten that turnsResult<Result<T, E1>, E2>
into aResult<T, E>
to properly notice the inner errors.As for cancelling tasks, you can use a broadcast channel combined with
select!
to cancel many…