tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
26.59k stars 2.45k forks source link

Identify if thread being created is a worker or blocking in `thread_name_fn` #6646

Closed dinhani closed 1 month ago

dinhani commented 3 months ago

Is your feature request related to a problem? Please describe. No. It is something that will help us debug code identifying when blocking code that should always be executed with spawn_blocking is being executed by worker threads and blocking all the other futures.

Describe the solution you'd like thread_name_fn should receive a parameter to indicate if the thread being created is a working thread or a blocking thread.

Alternatively we could have a method for worker threads and another one for blocking threads.

Describe alternatives you've considered

I am using this workaround to achieve the desired behavior, but it is not very robust.

.thread_name_fn(move || {
    // Tokio first create all async threads, then all blocking threads.
    // Threads are not expected to die because Tokio catches panics and blocking threads are configured to never die.
    // If one of these premises are not true anymore, this will possibly categorize threads wrongly.

    static ASYNC_ID: AtomicUsize = AtomicUsize::new(1);
    static BLOCKING_ID: AtomicUsize = AtomicUsize::new(1);

    // identify async threads
    let async_id = ASYNC_ID.fetch_add(1, Ordering::SeqCst);
    if async_id <= num_async_threads {
        return format!("tokio-async-{}", async_id);
    }

    // identify blocking threads
    let blocking_id = BLOCKING_ID.fetch_add(1, Ordering::SeqCst);
    format!("tokio-blocking-{}", blocking_id)
})             

Additional context ...

Darksonn commented 3 months ago

Unfortunately, if block_in_place is being used, a thread that used to be a blocking thread can become a worker thread, and vice-versa.

Darksonn commented 1 month ago

Closing as infeasible.