Tokio 當前執行緒任務

2022-09-26 04:27:14 字數 918 閱讀 3980

參考:

block_on 方法可以接收乙個非同步任務,在當前執行緒中執行並阻塞直到完成。

runtime::new()建立的執行時,會有乙個主線程和 cpu 邏輯核數相等工作執行緒。

use std::;

use tokio::runtime::runtime;

fn main() -> io::result<()> ", thread::current().name().unwrap());

});println!("{}", thread::current().name().unwrap());

runtime.shutdown_timeout(duration::from_secs(4));

ok(())

}

可以看到都是在主線程中執行的,執行緒的名稱都是 main。

hello tokio

main

main

use std::;

use tokio::runtime::runtime;

fn main() -> io::result<()> ", thread::current().name().unwrap());

44});

println!("{}", result);

println!("{}", thread::current().name().unwrap());

runtime.shutdown_timeout(duration::from_secs(4));

ok(())

}

提交給block_on的任務,會在主線程中執行,並且會一直阻塞,直到任務完成才往下執行。

Tokio 阻塞執行緒任務

參考 spawn blocking方法可以接收乙個閉包,可以是乙個阻塞任務。tokio 有兩種執行緒。一種給非同步任務的核心執行緒,一種是執行同步任務的阻塞執行緒。核心執行緒池的數量和 cpu 核數相同,阻塞執行緒只有在需要的時候新建。use std use tokio runtime runtim...

如何中斷當前執行緒

中斷當前執行緒有兩種方式。第一種方式是通過呼叫執行緒的stop 方法,第二種方式通過呼叫interrupt 方法。由於第一種方式是不安全的,所以本篇文章不做討論,主要分享一下如何使用interrupt 方法來中斷執行緒。thread類中提供了三個中斷執行緒的方法,如下圖 方法詳情 public cl...

Windows Linux下獲取當前執行緒的ID號

序 在多執行緒場合,為了方便跟蹤執行緒的執行狀態,往往需要在程式中新增列印當前執行緒id號的功能。1.linux下列印當前執行緒idpthread t pthread self 2.windows下列印當前執行緒iddword getcurrentthreadid ifdef win32 inclu...