【发布时间】:2020-04-18 16:20:35
【问题描述】:
use std::thread;
use tokio::task; // 0.3.4
#[tokio::main]
async fn main() {
thread::spawn(|| {
task::spawn(async {
println!("123");
});
})
.join();
}
编译时出现警告:
warning: unused `std::result::Result` that must be used
--> src/main.rs:6:5
|
6 | / thread::spawn(|| {
7 | | task::spawn(async {
8 | | println!("123");
9 | | });
10 | | })
11 | | .join();
| |____________^
|
= note: `#[warn(unused_must_use)]` on by default
= note: this `Result` may be an `Err` variant, which should be handled
在执行时出现错误:
thread '<unnamed>' panicked at 'must be called from the context of Tokio runtime configured with either `basic_scheduler` or `threaded_scheduler`', src/main.rs:7:9
【问题讨论】:
-
您在这里的实际目标是什么?你为什么要在不同的线程上生成该任务?我认为答案真的取决于你想做什么。
-
@Frxstrem 我需要从非主线程 (t) 启动另一个线程,并且线程 (t) 应该继续运行。在此之前,我使用了线程池。 repl.it/repls/AssuredWellmadeParentheses 之类的东西现在我决定用 async/await Tokio 替换池
-
真正的问题是:为什么要混合线程和任务?
-
如果你使用tokio,最好到处使用。任务不是线程,不能从任何地方产生,只能从由 tokio 管理的线程产生。您也许可以使用 tokio 通道在两者之间进行通信,但这是大量的额外工作和非常不同的代码结构
-
您需要获取运行时的句柄,您可以将其传递给线程。您可能必须手动创建运行时才能执行此操作。然后句柄将处理将任务从调用它的线程编组到 tokio 工作线程。
标签: asynchronous rust rust-tokio