Replace once-cell with async-lock (#241)

* Replace once-cell with async-lock

* Update dependencies
This commit is contained in:
John Nunley 2022-11-27 20:39:36 -08:00 committed by GitHub
parent 78d512a277
commit 8e97a4477e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 26 deletions

View File

@ -18,15 +18,14 @@ exclude = ["/.*"]
[dependencies] [dependencies]
async-channel = "1.4.2" async-channel = "1.4.2"
async-executor = "1.3.0" async-executor = "1.5.0"
async-fs = "1.3.0" async-fs = "1.3.0"
async-io = "1.1.2" async-io = "1.12.0"
async-lock = "2.3.0" async-lock = "2.6.0"
async-net = "1.4.3" async-net = "1.4.3"
async-process = "1.0.0" async-process = "1.6.0"
blocking = "1.0.0" blocking = "1.3.0"
futures-lite = "1.11.0" futures-lite = "1.11.0"
once_cell = "1.4.1"
[dev-dependencies] [dev-dependencies]
anyhow = "1" anyhow = "1"

View File

@ -4,8 +4,8 @@ use std::thread;
use async_executor::{Executor, Task}; use async_executor::{Executor, Task};
use async_io::block_on; use async_io::block_on;
use async_lock::OnceCell;
use futures_lite::future; use futures_lite::future;
use once_cell::sync::Lazy;
/// Spawns a task onto the global executor (single-threaded by default). /// Spawns a task onto the global executor (single-threaded by default).
/// ///
@ -28,26 +28,30 @@ use once_cell::sync::Lazy;
/// }); /// });
/// ``` /// ```
pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> { pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
static GLOBAL: Lazy<Executor<'_>> = Lazy::new(|| { static GLOBAL: OnceCell<Executor<'_>> = OnceCell::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)
};
for n in 1..=num_threads { fn global() -> &'static Executor<'static> {
thread::Builder::new() GLOBAL.get_or_init_blocking(|| {
.name(format!("smol-{}", n)) let num_threads = {
.spawn(|| loop { // Parse SMOL_THREADS or default to 1.
catch_unwind(|| block_on(GLOBAL.run(future::pending::<()>()))).ok(); std::env::var("SMOL_THREADS")
}) .ok()
.expect("cannot spawn executor thread"); .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)
} }