task: clarify when to use spawn_blocking vs dedicated threads (#7923)

This commit is contained in:
0rlych1kk4
2026-02-20 22:19:27 +08:00
committed by GitHub
parent 09f92b5aed
commit 1b11840f53

View File

@@ -119,6 +119,21 @@ cfg_rt! {
/// returns. It is possible for a blocking task to be cancelled if it has
/// not yet started running, but this is not guaranteed.
///
/// # When to use `spawn_blocking` vs dedicated threads
///
/// `spawn_blocking` is intended for *bounded* blocking work that eventually finishes.
/// Each call occupies a thread from the runtime's blocking thread pool for the duration
/// of the task. Long-lived tasks therefore reduce the pool's effective capacity, which
/// can delay other blocking operations once the pool is saturated and work is queued.
///
/// For workloads that run indefinitely or for extended periods (for example,
/// background workers or persistent processing loops), prefer a dedicated thread created with
/// [`thread::spawn`].
///
/// As a rule of thumb:
/// - Use `spawn_blocking` for short-lived blocking operations
/// - Use dedicated threads for long-lived or persistent blocking workloads
///
/// Note that if you are using the single threaded runtime, this function will
/// still spawn additional threads for blocking operations. The current-thread
/// scheduler's single thread is only used for asynchronous code.