Do I need to spawn to take advantage of a multi-threaded runtime? #3235
-
Hi, let mut runtime = tokio::runtime::Builder::new()
.threaded_scheduler()
// .max_threads(8)
.enable_all()
.build()
.unwrap();
runtime.block_on(worker::run(concurrency)); // worker.rs
pub async fn run(concurrency: usize) {
let (mut tx, rx) = mpsc::channel(concurrency);
let client = Client::new();
tokio::spawn(async move {
for i in 0..100 {
println!("sending task: {}", i);
tx.send(Task {
event: "https://kerkour.fr".into(),
payload: i.to_string(),
})
.await
.unwrap();
}
drop(tx);
});
let consumer_stream = rx.for_each_concurrent(concurrency, |task| {
let client = &client;
println!("received request({:?})", &task.payload);
async move {
let resp = client.get(&task.event).send().await.unwrap();
let _ = resp.text().await.unwrap();
println!("completed request({:?})", task.payload);
}
});
consumer_stream.await;
} From what I understood from https://tokio.rs/blog/2019-10-scheduler the scheduler automatically balance the futures across all So do I need to manually use multiple spawn calls to multi-thread the code above? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
The scheduler doesn't automatically balance futures across all core threads, it balances tasks. Tasks are lightweight units of work composed of one or more futures. Calling Therefore, yes, in order to run work in parallel on multiple threads, it is necessary to spawn new tasks. Does that help? |
Beta Was this translation helpful? Give feedback.
-
Another quick question @hawkw : i.e Are |
Beta Was this translation helpful? Give feedback.
The scheduler doesn't automatically balance futures across all core threads, it balances tasks. Tasks are lightweight units of work composed of one or more futures. Calling
tokio::spawn
ortokio::spawn_local
with a future creates a new task that executes that future.await
ing a future in anasync
block or function waits for that future to complete as part of the current task.Therefore, yes, in order to run work in parallel on multiple threads, it is necessary to spawn new tasks. Does that help?