From e0323e34bc7b395d02b6e97366c54441bbcd86f7 Mon Sep 17 00:00:00 2001 From: Sebastian Martinez Date: Fri, 25 Oct 2024 12:48:33 +0200 Subject: [PATCH] Use `tokio::time::sleep` instead of blocking threads Great explanation by @LarsWirzenius on the why > Async code in Rust runs in one or more threads. Usually there's a small number of threads that are multiplexed between different async functions. The async executor chooses what threads to use and which thread runs which async code. If the async code takes a long time, such as by calling std::thread::sleep, the whole thread stops doing anything else, and then no other async code runs in that thread, either. --- Cargo.lock | 1 + crates/radicle-tauri/Cargo.toml | 1 + crates/radicle-tauri/src/lib.rs | 4 ++-- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0a5e3ec77..efb18a772 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4006,6 +4006,7 @@ dependencies = [ "tauri-plugin-shell", "tauri-plugin-window-state", "thiserror", + "tokio", "ts-rs", ] diff --git a/crates/radicle-tauri/Cargo.toml b/crates/radicle-tauri/Cargo.toml index 9019f4fcf..352b8c7a8 100644 --- a/crates/radicle-tauri/Cargo.toml +++ b/crates/radicle-tauri/Cargo.toml @@ -31,6 +31,7 @@ tauri-plugin-shell = { version = "2.0.1" } tauri-plugin-window-state = { version = "2.0.1" } thiserror = { version = "1.0.64" } ts-rs = { version = "10.0.0", features = ["serde-json-impl", "no-serde-warnings"] } +tokio = { version = "1.40.0", features = ["time"] } [features] # by default Tauri runs in production mode diff --git a/crates/radicle-tauri/src/lib.rs b/crates/radicle-tauri/src/lib.rs index 507567796..ea2a03ae4 100644 --- a/crates/radicle-tauri/src/lib.rs +++ b/crates/radicle-tauri/src/lib.rs @@ -45,7 +45,7 @@ pub fn run() { tauri::async_runtime::spawn(async move { loop { let _ = node_handler.emit("node_running", node_status.is_running()); - std::thread::sleep(std::time::Duration::from_secs(2)); + tokio::time::sleep(std::time::Duration::from_secs(2)).await; } }); @@ -61,7 +61,7 @@ pub fn run() { log::debug!("node: event subscription loop has exited."); } - std::thread::sleep(std::time::Duration::from_secs(2)); + tokio::time::sleep(std::time::Duration::from_secs(2)).await; } });