concurrency

This commit is contained in:
Jon Janzen
2021-08-23 19:17:17 -06:00
parent ccfff11c8e
commit e50060412c

View File

@@ -1,7 +1,9 @@
use color_eyre::Report; use color_eyre::Report;
use reqwest::Client; use reqwest::Client;
use tokio::time::sleep;
use tracing::info; use tracing::info;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use std::time::Duration;
pub const URL_1: &str = "https://fasterthanli.me/articles/whats-in-the-box"; pub const URL_1: &str = "https://fasterthanli.me/articles/whats-in-the-box";
@@ -12,12 +14,14 @@ async fn main() -> Result<(), Report> {
setup()?; setup()?;
let client = Client::new(); let client = Client::new();
let leaked_client = Box::leak(Box::new(client));
let fut1 = fetch_thing(&client, URL_1); let fut1 = fetch_thing(leaked_client, URL_1);
let fut2 = fetch_thing(&client, URL_2); tokio::spawn(fut1);
let fut2 = fetch_thing(leaked_client, URL_2);
tokio::spawn(fut2);
fut1.await?; tokio::time::sleep(Duration::from_secs(1)).await;
fut2.await?;
Ok(()) Ok(())
} }
@@ -45,10 +49,10 @@ fn setup() -> Result<(), Report> {
// } // }
// //
use std::future::Future; use std::future::Future;
fn fetch_thing<'a> ( fn fetch_thing (
client: &'a Client, client: &'static Client,
url: &'a str, url: &'static str,
) -> impl Future<Output = Result<(), Report>> + 'a { ) -> impl Future<Output = Result<(), Report>> + 'static {
async move { async move {
let res = client.get(url).send().await?.error_for_status()?; let res = client.get(url).send().await?.error_for_status()?;
info!(%url, content_type = ?res.headers().get("content-type"), "Got a response!"); info!(%url, content_type = ?res.headers().get("content-type"), "Got a response!");