How does current_thread
runtime work?
#6987
-
So I came across this discussion and got confused: so the I/O and timer drivers of What I don't understand is why then this slightly modified snippet doesn't suffer similar issue? At first, I assumed the program is doing something like this: the runtime lives on thread So t2 is later than t1, i.e. new task is appended to the runtime task queue (which again lives on How does the task even got I tried to explain the behavior by adding the Is tokio doing something akin to such an explanation? I mean use tokio::*;
#[tokio::main(flavor = "current_thread")]
async fn main() {
// let's call this thread `m` for `main`
println!("Thread `m` has ID thread {:?}", std::thread::current().id());
call_sync();
println!("main thread finished!");
}
pub fn call_sync() {
let handle = runtime::Handle::current();
// let's call this spawned thread `s`
let thread_s_result = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(10));
handle.block_on(async_print())
})
.join();
println!("{thread_s_result:?}");
}
pub async fn async_print() {
async {
println!(
"I'm in async block, thread {:?}",
std::thread::current().id()
);
}
.await
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Since this time your program uses |
Beta Was this translation helpful? Give feedback.
When you use
Handle::block_on
, then that will execute the future you pass it, but the thread is not otherwise part of the runtime. No other futures are executed there. This applies to both current-thread and multi-thread.Note that
Runtime::block_on
is slightly different. There, with the current-thread runtime, one of theblock_on
calls becomes where the real runtime is running. Any extra calls are just likeHandle::block_on
in that they execute the future they're given and nothing else.