tokio 什么时候生成线程? [英] When does tokio spawn threads?

查看:76
本文介绍了tokio 什么时候生成线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的代码有

#[tokio::main]异步 fn main() {//改变一个全局只读变量不安全";

全局只读变量的变化会在 Tokio 设置其线程池之前还是之后发生?

解决方案

来自 tokio 文档:

<块引用>

#[tokio::main]异步 fn main() {println!(你好世界");}

不使用#[tokio::main]

的等效代码

fn main() {tokio::runtime::Builder::new_multi_thread().enable_all().建造().解包().block_on(异步{println!(你好世界");})}

所以 async fn main() 中的代码在执行器启动后由执行器运行.

If my code has

#[tokio::main]
async fn main() {
  // mutates a global read-only variable "unsafe"

Will that mutation on the global read-only variable happen before or after Tokio sets up its thread pool?

解决方案

From the tokio documentation:

#[tokio::main]
async fn main() {
    println!("Hello world");
}

Equivalent code not using #[tokio::main]

fn main() {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            println!("Hello world");
        })
}

So the code in async fn main() is run by the executor, after its been started.

这篇关于tokio 什么时候生成线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆