mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-04-17 22:14:36 +00:00
task: clarify when to use spawn_blocking vs dedicated threads (#7923)
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user