async-rs / async-rs/async-std

blocking on spawn not work as intended

Open
#740 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
4.1k
Forks
339
PR merge metrics
No merged PRs in 30d

Description

in the [blog] it is said that:
> The runtime measures the time it takes to perform the blocking operation and if it takes a while, a new thread is automatically spawned and replaces the old executor thread. That way, only the current task is blocked on the operation rather than the whole executor thread or the whole runtime. If the blocking operation is quick, we don’t spawn a new thread and therefore no additional cost is inflicted.

so I tried to block all available thread (my machine has 4 core), but after a while, I don't see any new thread is spawned

```rust
use async_std::task; // version 1.5.0
use std::time::Duration;

fn main() {
task::block_on(async {
let num = num_cpus::get();
let mut handlers = Vec::with_capacity(num * 2);

for i in 1..=num {
handlers.push(task::spawn(blocking_work(i)));
handlers.push(task::spawn(normal_work(i)));
}

for h in handlers.into_iter() {
h.await
}
})
}

async fn blocking_work(i: usize) {
loop {
std::thread::sleep(Duration::from_secs(5));
println!("blocking_work {}", i)
}
}

async fn normal_work(i: usize) {
loop {
task::sleep(Duration::from_secs(1)).await;
println!("normal_work {}", i)
}
}
```

shouldn't runtime spawn more OS thread for this?

[blog]: https://async.rs/blog/stop-worrying-about-blocking-the-new-async-std-runtime/

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.