常见坑
这一章给从搜索引擎进来的读者:手里有一句报错或者一个现象,想知道为什么、怎么改。每页结构相同:
- 能触发问题的最小代码,和它的真实输出(编译错误就是 rustc 的原文)。
- 这句报错在 tokio 源码的哪里,为什么要这么查。只给出处,原理链接到前面的章节。
- 几种改法,各自适合什么情况。
flowchart TB
s{看到了什么}
s -->|运行时 panic| p[第 1、2、5 页]
s -->|编译错误| c[第 3 页]
s -->|没报错,但慢或卡| b[第 4 页]
s -->|不知道选哪把锁| m[第 6 页]
s -->|数据丢了| x[第 7 页]
| 症状 | 页面 |
|---|---|
there is no reactor running, must be called from the context of a Tokio 1.x runtime | 1. there is no reactor running |
A Tokio 1.x context was found, but timers are disabled / but IO is disabled | 1. there is no reactor running |
Cannot start a runtime from within a runtime | 2. Cannot start a runtime from within a runtime |
Cannot drop a runtime in a context where blocking is not allowed | 2. Cannot start a runtime from within a runtime |
Cannot block the current thread from within a runtime(blocking_recv、blocking_lock) | 2. Cannot start a runtime from within a runtime |
编译错误 future cannot be sent between threads safely,提示 MutexGuard 或 Rc 不是 Send | 3. future cannot be sent between threads safely |
| 没有报错,但别的任务延迟几百毫秒、定时器不准、刚 spawn 的任务迟迟不跑 | 4. 在 async 里阻塞 |
can call blocking only when running on the multi-threaded runtime(多见于 #[tokio::test]) | 5. can call blocking only when running on the multi-threaded runtime |
不确定该用 tokio::sync::Mutex 还是 std::sync::Mutex | 6. tokio::sync::Mutex 还是 std::sync::Mutex |
select! 循环里偶尔丢消息、丢半行数据,或者某个分支永远完成不了 | 7. select! 的取消安全 |
前三句 panic 都来自同一个线程本地变量 CONTEXT,原理在线程本地上下文一页讲过。这里只讲碰到时怎么改。
所有实验在 Apple M2 Max(12 核)、rustc 1.99.0、tokio 1.54.1 上运行,release 构建。时间类的数字在别的机器上会不同,量级和结论不变。
💬 关联讨论
发起讨论加载中...