From 8e97a4477e52ffa07b818b42be0c3e1d078711e8 Mon Sep 17 00:00:00 2001 From: John Nunley Date: Sun, 27 Nov 2022 20:39:36 -0800 Subject: [PATCH] Replace once-cell with async-lock (#241) * Replace once-cell with async-lock * Update dependencies --- Cargo.toml | 11 +++++------ src/spawn.rs | 44 ++++++++++++++++++++++++-------------------- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ea37acb..e8868cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,15 +18,14 @@ exclude = ["/.*"] [dependencies] async-channel = "1.4.2" -async-executor = "1.3.0" +async-executor = "1.5.0" async-fs = "1.3.0" -async-io = "1.1.2" -async-lock = "2.3.0" +async-io = "1.12.0" +async-lock = "2.6.0" async-net = "1.4.3" -async-process = "1.0.0" -blocking = "1.0.0" +async-process = "1.6.0" +blocking = "1.3.0" futures-lite = "1.11.0" -once_cell = "1.4.1" [dev-dependencies] anyhow = "1" diff --git a/src/spawn.rs b/src/spawn.rs index e01d0d0..4741948 100644 --- a/src/spawn.rs +++ b/src/spawn.rs @@ -4,8 +4,8 @@ use std::thread; use async_executor::{Executor, Task}; use async_io::block_on; +use async_lock::OnceCell; use futures_lite::future; -use once_cell::sync::Lazy; /// Spawns a task onto the global executor (single-threaded by default). /// @@ -28,26 +28,30 @@ use once_cell::sync::Lazy; /// }); /// ``` pub fn spawn(future: impl Future + Send + 'static) -> Task { - static GLOBAL: Lazy> = Lazy::new(|| { - let num_threads = { - // Parse SMOL_THREADS or default to 1. - std::env::var("SMOL_THREADS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(1) - }; + static GLOBAL: OnceCell> = OnceCell::new(); - for n in 1..=num_threads { - thread::Builder::new() - .name(format!("smol-{}", n)) - .spawn(|| loop { - catch_unwind(|| block_on(GLOBAL.run(future::pending::<()>()))).ok(); - }) - .expect("cannot spawn executor thread"); - } + fn global() -> &'static Executor<'static> { + GLOBAL.get_or_init_blocking(|| { + let num_threads = { + // Parse SMOL_THREADS or default to 1. + std::env::var("SMOL_THREADS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(1) + }; - Executor::new() - }); + for n in 1..=num_threads { + thread::Builder::new() + .name(format!("smol-{}", n)) + .spawn(|| loop { + catch_unwind(|| block_on(global().run(future::pending::<()>()))).ok(); + }) + .expect("cannot spawn executor thread"); + } - GLOBAL.spawn(future) + Executor::new() + }) + } + + global().spawn(future) }