小弧光的博客

公众号:小弧光黑板报

导航

rust tokio 使用

1、 主函数使用

new 一个 Runtime:


let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();

rt.block_on(async move {

// some task with loop inner

loop{

}

});

let runtime = tokio::runtime::Builder::new_current_thread().build()?;

block_on 方法非常常用,可以用于在同步方法中调用异步方法。

2、 启动一个 async task


tokio::spawn(async move {

// a timer

let mut interval = time::interval(time::Duration::from_secs(5));

loop {

interval.tick().await;

}

});

3、oneshot channel


let (close_tx, close_rx) = oneshot::channel();

4、TokioMutex

5、 Handle


/// Returns a handle to the runtime's spawner.

///

/// The returned handle can be used to spawn tasks that run on this runtime, and can

/// be cloned to allow moving the `Handle` to other threads.

///

/// # Examples

use tokio::runtime::Runtime;



let rt = Runtime::new()

.unwrap();



let handle = rt.handle();

可以基于这个 handle 启动一个 task:


rt.spawn(async move {

///

});

6、#[tokio::main] 标注启动 async main


#[tokio::main]

pub async fn main() {

println!("Hello world");

}

等价于


fn main() {

tokio::runtime::Builder::new_multi_thread()

.enable_all()

.build()

.unwrap()

.block_on(async {

println!("Hello world");

})

}

7、tokio::task::spawn_blocking

8、tokio::time::sleep(Duration::new(1, 0)).await;

9、signal


struct ExitSignal(pub &'static str);



async fn listen_for_signals() -> Result<ExitSignal, String> {

let mut term_sig = signal(SignalKind::terminate())

.map_err(|e| format!("could not listen for TERM signals: {}", e))?;

let mut int_sig = signal(SignalKind::interrupt())

.map_err(|e| format!("Could not listen for INT signal: {}", e))?;



let sig_name = tokio::select! {

Some(_signal) = term_sig.recv() => {

"SIG_TERM"

},

Some(_signal) = int_sig.recv() => {

"SIG_INT"

},

};

Ok(ExitSignal(sig_name))

}

10、

posted on 2022-12-09 15:33  小弧光  阅读(761)  评论(0编辑  收藏  举报