diff options
author | hozan23 <hozan23@proton.me> | 2024-03-20 15:20:21 +0100 |
---|---|---|
committer | hozan23 <hozan23@proton.me> | 2024-03-20 15:20:21 +0100 |
commit | 379dca552ca91d22ee007b42f93803ad3dc2b274 (patch) | |
tree | 1ba10573b6ec5213baf46f6ab9c3767e0daa4eed /core/src/async_util/executor.rs | |
parent | 340957fec147f4429796413f27bbd9b84ba6f141 (diff) |
core: add the option to create a new task group without providing an
executor & remove GlobalExecutor type
Diffstat (limited to 'core/src/async_util/executor.rs')
-rw-r--r-- | core/src/async_util/executor.rs | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/core/src/async_util/executor.rs b/core/src/async_util/executor.rs new file mode 100644 index 0000000..3e7aa06 --- /dev/null +++ b/core/src/async_util/executor.rs @@ -0,0 +1,30 @@ +use std::{panic::catch_unwind, sync::Arc, thread}; + +use async_lock::OnceCell; +use smol::Executor as SmolEx; + +static GLOBAL_EXECUTOR: OnceCell<Arc<smol::Executor<'_>>> = OnceCell::new(); + +/// A pointer to an Executor +pub type Executor<'a> = Arc<SmolEx<'a>>; + +/// Returns a single-threaded global executor +pub(crate) fn global_executor() -> Executor<'static> { + fn init_executor() -> Executor<'static> { + let ex = smol::Executor::new(); + thread::Builder::new() + .spawn(|| loop { + catch_unwind(|| { + smol::block_on(global_executor().run(smol::future::pending::<()>())) + }) + .ok(); + }) + .expect("cannot spawn executor thread"); + // Prevent spawning another thread by running the process driver on this + // thread. see https://github.com/smol-rs/smol/blob/master/src/spawn.rs + ex.spawn(async_process::driver()).detach(); + Arc::new(ex) + } + + GLOBAL_EXECUTOR.get_or_init_blocking(init_executor).clone() +} |