Created
May 27, 2020 21:05
-
-
Save davidbarsky/5f568a4c1cd048b79003e37feddad7cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![deny(rust_2018_idioms)] | |
/// This is a example showing how information is scoped with tokio's | |
/// `task::spawn`. | |
/// | |
/// You can run this example by running the following command in a terminal | |
/// | |
/// ``` | |
/// cargo run --example tokio-spawny-thing | |
/// ``` | |
use futures::stream::{FuturesUnordered, StreamExt}; | |
use tracing::{debug, info, instrument, span, Level}; | |
use tracing_futures::Instrument; | |
type Error = Box<dyn std::error::Error + Send + Sync + 'static>; | |
#[instrument] | |
async fn parent_task(subtasks: usize) -> Result<(), Error> { | |
info!("spawning subtasks..."); | |
let mut subtasks = (1..=subtasks) | |
.map(|number| { | |
let span = span!(Level::INFO, "subtask", %number); | |
debug!(message = "creating subtask;", number); | |
tokio::spawn(subtask(number).instrument(span)) | |
}) | |
.collect::<FuturesUnordered<_>>(); | |
let mut sum: usize = 0; | |
while let Some(handle) = subtasks.next().await { | |
let handle = handle?; | |
sum += handle; | |
} | |
info!(%sum, "all subtasks completed; calculated sum"); | |
Ok(()) | |
} | |
async fn subtask(number: usize) -> usize { | |
info!("polling subtask..."); | |
number | |
} | |
#[tokio::main] | |
async fn main() -> Result<(), Error> { | |
tracing_subscriber::fmt() | |
.with_max_level(tracing::Level::DEBUG) | |
.try_init()?; | |
parent_task(10).await?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment