What the overhead of new_multi_thread()?

The following code are my IO function like:

fn read(...) {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            async_network_IO();
        })
}

I want call async function in my sync function read() and let it block the caller thread until async_network_IO() complete.

But the question is, what the overhead of new_multi_thread()?

Given:

  • As a IO function, read() could be called for many times.
  • read() is called in a user-created thread;

Are there better way to go?

Got it! I should use async_std::task::block_on.

async_std can do the job. Just keep in mind that you should avoid mixing async_std and tokio together.

You can spawn a tokio runtime sometime earlier, and save a Handle::current() to be able to use this runtime somewhere else, and then use Handle.block_on().

Thanks!

By the way, what would happen if I call runtime.block_on() on one Arc<tokio::Runtime> from multiple threads?

    let runtime = Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    let runtime_ref1 = Arc::new(runtime);
    let runtime_ref2 = runtime_ref.clone();

    let thread1 = thread::spawn(move || {
        runtime_ref1.block_on( ... );
    });

    let thread2 = thread::spawn(move || {
        runtime_ref2.block_on( ... );
    });

I notice the following comment lines in tokio build-in file tokio-1.35.0/src/runtime/runtime.rs

/// Calling [`Handle::block_on`] on a handle to a `current_thread` runtime is error-prone.
/// Refer to the documentation of [`Handle::block_on`] for more.

It seemed that tokio disagree block_on current_thread. But what if I intend to block my thread?

That will work just fine.

This comment is specific to Handle::block_on, which is different from Runtime::block_on.

See the documentation for an explanation:

When this is used on a current_thread runtime, only the Runtime::block_on method can drive the IO and timer drivers, but the Handle::block_on method cannot drive them. This means that, when using this method on a current_thread runtime, anything that relies on IO or timers will not work unless there is another thread currently calling Runtime::block_on on the same runtime.