BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / runtime.rs

runtime.rs

refactor(app): extract app-base crate
metis Daniel Däschle · pushed by metis · 6 weeks ago
16e522c2 History
runtime.rs 1.3 KiB Download Raw
1use std::future::Future;
2use std::sync::OnceLock;
3
4use tokio::runtime::{Builder, Runtime};
5use tokio::sync::oneshot;
6
7static RUNTIME: OnceLock<Runtime> = OnceLock::new();
8
9fn runtime() -> &'static Runtime {
10 RUNTIME.get_or_init(|| {
11 Builder::new_multi_thread()
12 .worker_threads(4)
13 .thread_name("teams-net")
14 .enable_all()
15 .build()
16 .expect("tokio runtime")
17 })
18}
19
20pub fn handle() -> tokio::runtime::Handle {
21 runtime().handle().clone()
22}
23
24/// Runs the future on the network runtime. The receiver is runtime-agnostic, so the GPUI executor can await it.
25pub fn spawn<T: Send + 'static>(
26 future: impl Future<Output = T> + Send + 'static,
27) -> oneshot::Receiver<T> {
28 let (sender, receiver) = oneshot::channel();
29 runtime().spawn(async move {
30 let _ = sender.send(future.await);
31 });
32 receiver
33}
34
35/// Like `spawn`, plus a handle that stops the future at its next await point.
36pub fn spawn_abortable<T: Send + 'static>(
37 future: impl Future<Output = T> + Send + 'static,
38) -> (oneshot::Receiver<T>, tokio::task::AbortHandle) {
39 let (sender, receiver) = oneshot::channel();
40 let task = runtime().spawn(async move {
41 let _ = sender.send(future.await);
42 });
43 (receiver, task.abort_handle())
44}