Skip to content

Commit

Permalink
changed async example to use spawn_blocking
Browse files Browse the repository at this point in the history
The correct way to call blocking code in tokio is through the spawn_blocking mechanism to prevent all threads from being exhausted to perform async operations. See below for details.
look [here](https://users.rust-lang.org/t/nano-get-minimalistic-http-s-get-crate/37264/2?u=rapidclock)
  • Loading branch information
rapidclock authored Jan 22, 2020
1 parent 6ed05ec commit e92d9b5
Showing 1 changed file with 5 additions and 10 deletions.
15 changes: 5 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
[![Crates.io](https://img.shields.io/crates/v/nano-get.svg)](https://crates.io/crates/nano-get)
[![Docs.rs](https://docs.rs/nano-get/badge.svg)](https://docs.rs/nano-get)

A tiny implementation of HTTP GET using only the standard library by default.
A minimalistic implementation of HTTP GET using only the standard library by default.

If you require `https`, please enable the `"https"` feature flag like:
```
Expand Down Expand Up @@ -121,7 +121,7 @@ This is also not meant to be demonstrative of idiomatic uses of the async librar
```toml
[dependencies]
nano-get = {version = "0.2.3", features = ["https"] }
tokio = { version = "0.2.6", features = ["rt-threaded"] }
tokio = { version = "0.2.10", features = ["blocking", "rt-threaded"] }
futures = "0.3.1"
```

Expand All @@ -135,7 +135,6 @@ use std::time::Instant;

use tokio::runtime::{Runtime, Builder};
use futures::future::try_join_all;
use nano_get::get;

fn main() {
let mut runtime: Runtime = Builder::new().threaded_scheduler().build().unwrap();
Expand All @@ -145,7 +144,7 @@ fn main() {
let start = Instant::now();
for i in 1..=100 {
let url = format!("{}/{}", base_url, i);
handles.push(tokio::spawn(get_url(url)));
handles.push(tokio::task::spawn_blocking(move || nano_get::get(url)));
}
let responses: Vec<String> = try_join_all(handles).await.unwrap();
let duration = start.elapsed();
Expand All @@ -154,10 +153,6 @@ fn main() {
println!("Average time for get is: {}s", duration.as_secs_f64() / (responses.len() as f64));
});
}

async fn get_url(url: String) -> String {
get(url)
}
```

**example output**
Expand All @@ -168,6 +163,6 @@ async fn get_url(url: String) -> String {
"id": 100,
"title": "enim repellat iste"
}
Time elapsed in http get is: 3.671184788s
Average time for get is: 0.03671184788s
Time elapsed in http get is: 1.171043748s
Average time for get is: 0.01171043748s
```

0 comments on commit e92d9b5

Please sign in to comment.