From 30ed2ac829eff3d035fecf1e72229bc0560e6e3e Mon Sep 17 00:00:00 2001 From: Tunglies Date: Wed, 15 Apr 2026 01:38:19 -0700 Subject: [PATCH] feat(runtime): cap tokio worker threads at 16 and scale blocking threads (#6261) This prevents the runtime from spawning an excessive number of threads on high-end CPUs, reducing memory footprint and context switching. Introduces a dynamic cap for worker threads (max 16) and scales blocking threads proportionally. Includes thread naming for diagnostics. --- src-tauri/src/lib.rs | 1 + src-tauri/src/main.rs | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index efb8ae042..bf5aa7453 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -10,6 +10,7 @@ mod feat; mod module; mod process; pub mod utils; + use crate::constants::files; use crate::{ core::handle, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index fa3c6905e..f7961121f 100755 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,5 +1,27 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +use std::sync::atomic::{AtomicUsize, Ordering}; + fn main() { + let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); + let worker_limit = std::cmp::min(default_parallelism, 16); + let blocking_limit = 4 * worker_limit; + + #[allow(clippy::unwrap_used)] + let tokio_runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(worker_limit) + .max_blocking_threads(blocking_limit) + .enable_all() + .thread_name_fn(|| { + static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); + let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); + format!("clash-verge-runtime-{id}") + }) + .build() + .unwrap(); + let tokio_handle = tokio_runtime.handle(); + tauri::async_runtime::set(tokio_handle.clone()); + #[cfg(feature = "tokio-trace")] console_subscriber::init();