├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── doc ├── AsyncInDepth.md ├── BridgingWithSyncCode.md ├── Channels.md ├── Framing.md ├── Glossary.md ├── GracefulShutdown.md ├── HelloTokio.md ├── IO.md ├── Introduction.md ├── Select.md ├── SharedState.md ├── Spawning.md ├── Streams.md └── Topics.md └── src ├── bin ├── channels-demo.rs ├── common │ ├── delay.rs │ └── mod.rs ├── echo-client.rs ├── echo-server-copy.rs ├── echo-server.rs ├── future-impl-demo.rs ├── hello-redis-server.rs ├── hello-tokio.rs ├── io-demo.rs ├── mini-tokio-one.rs ├── mini-tokio-two.rs ├── mini-tokio.rs ├── my-future.rs ├── not-compile.rs ├── select-borrow.rs ├── select-demo.rs ├── select-syntax-demo.rs ├── send-bound.rs ├── shared-state.rs └── store-value.rs ├── main.rs ├── relational ├── connection.rs ├── frame_enum.rs └── mod.rs └── tools ├── mod.rs └── tools.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .idea 3 | Cargo.lock 4 | *.iml -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-cn-doc" 3 | version = "0.1.0" 4 | authors = ["dengshenglong "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | tokio = {version = "0.2", features = ["full"]} 11 | mini-redis = "0.2" 12 | bytes = "1.0.1" 13 | rand = "0.5.5" 14 | crossbeam = "0.7" 15 | futures = "0.3" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 dslchd 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tokio 中文文档 2 | ## 1.说明 3 | Tokio 它是Rust语言的一种异步**运行时** 可以用来编写可靠,异步的Rust应用. 它有以下几个特点: 4 | * 快速: Tokio是零成本抽象的,可以带给你接近裸机的性能. 5 | * 可靠的: Tokio基于Rust语言的生命周期,类型系统,并发模型来减少bug和确保线程安全. 6 | * 可扩展: Tokio有非常小的占用,并能处理背压(backpressure)和取消(cancellation)操作. 7 | 8 | Tokio是一个事件驱动的非阻塞I/O平台,用于使用Rust编写异步应用. 在较高的层次上,它提供了几个主要的组件: 9 | * 基于多线程与工作流窃取的 任务调度器 [scheduler](https://docs.rs/tokio/latest/tokio/runtime/index.html). 10 | * 响应式的,基于操作系统的事件队列(比如,epoll, kqueue, IOCP, 等...). 11 | * 异步的[TCP and UDP](https://docs.rs/tokio/latest/tokio/net/index.html) socket. 12 | 13 | 这些组件提供了用来构建异步应用所需要的运行时组件. 14 | 15 | [官方原文指南](https://tokio.rs/tokio/tutorial). 16 | 17 | [bin](src/bin) 目录下有一些可以参考的,基于官方文档的示例代码. 18 | 19 | 我的其它翻译:[Actix-web 3.0 中文文档](https://github.com/dslchd/actix-web3-CN-doc). 20 | 21 | ## 2.中文文档索引 22 | 23 | ### 指南 24 | #### [介绍(Introduction)](doc/Introduction.md) 25 | #### [你好 Tokio (Hello Tokio)](doc/HelloTokio.md) 26 | #### [Spawning](doc/Spawning.md) 27 | #### [共享状态(Shared state)](doc/SharedState.md) 28 | #### [通道(Channels)](doc/Channels.md) 29 | #### [I/O](doc/IO.md) 30 | #### [帧(Framing)](doc/Framing.md) 31 | #### [深入异步(Async in depth)](doc/AsyncInDepth.md) 32 | #### [Select](doc/Select.md) 33 | #### [流(Streams)](doc/Streams.md) 34 | ### [主题(Topics)](doc/Topics.md) 35 | #### [使用同步代码桥接(Bridging with sync code)](doc/BridgingWithSyncCode.md) 36 | #### [优雅关机(Graceful Shutdown)](doc/GracefulShutdown.md) 37 | ### [词汇表(Glossary)](doc/Glossary.md) 38 | ### [API文档(API documentation)](https://docs.rs/tokio) 39 | 40 | ## 3.其它 41 | Tokio是一个非常值得学习的,Rust生态中的网络库. 有些类似 "Rust界的Netty" 的感觉,很多上层库,或包,或框架都是基于它(比如 Actix-web). 42 | 因此作为一名 _Rustaceans_ 学习与使用,或理解Tokio意义重大. 此**中文文档**是本人在学习Tokio后的 **"果实"** . 我顺便整理了出来. 43 | 44 | 由于水平有限,不敢妄言翻译的有多好,其中难免会有错误和遗漏,如果发现烦请一并指正. 望此文档能给同样对Tokio感兴趣的人的学习带来一点帮助. 45 | -------------------------------------------------------------------------------- /doc/AsyncInDepth.md: -------------------------------------------------------------------------------- 1 | ## 深入异步(Async in depth) 2 | 到现在,我们完成了异步Rust和Tokio相当全面的介绍. 现在我们将更深入的研究Rust异步运行时模型. 在本教程最开始,我们暗示过Rust的异步采用了一种独特的方式. 现在我们将解释其含义. 3 | 4 | ## Futures 5 | 作为回顾,让我们写一个非常基础的异步函数. 与到目前为止的教程相比,这并不是什么新东西. 6 | 7 | ```rust 8 | use tokio::net::TcpStream; 9 | 10 | async fn my_async_fn() { 11 | println!("hello from async"); 12 | let _socket = TcpStream::connect("127.0.0.1:3000").await.unwrap(); 13 | println!("async TCP operation complete"); 14 | } 15 | ``` 16 | 17 | 我们调用这个函数并得到一些返回值. 我们调用`.await`得到这个值. 18 | 19 | ```rust 20 | #[tokio::main] 21 | async fn main() { 22 | let what_is_this = my_async_fn(); 23 | // 上面调用后,这里并没有任何打印内容 24 | what_is_this.await; 25 | // 文本被打印了,且socket链接建立和关闭 26 | } 27 | ``` 28 | 29 | `my_async_fn()` 返回的是一个future值. 此Future它是一个实现了标准库中 [std::future::Future](https://doc.rust-lang.org/std/future/trait.Future.html) trait 的值. 它们是包含正在进行异步计算的值. 30 | 31 | [std::future::Future](https://doc.rust-lang.org/std/future/trait.Future.html) trait定义如下: 32 | 33 | ```rust 34 | use std::pin::Pin; 35 | use std::task::{Context, Poll}; 36 | 37 | pub trait Future { 38 | type Output; 39 | 40 | fn poll(self: Pin<&mut Self>, cx:&mut Context) -> Poll; 41 | } 42 | ``` 43 | 44 | [associated type](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types) `Output` 是一个future完成后产生的类型. 45 | [Pin](https://doc.rust-lang.org/std/pin/index.html) 类型是Rust在 `async` 函数中如何支持借用. 查看 [standard library](https://doc.rust-lang.org/std/pin/index.html) 了解更多的细节. 46 | 与其它语言实现的future不一样, 一个Rust的future不代表在后台发生的计算,而是Rust的future就是计算本身. future的所有者通过轮询future来推进计算. 这是通过调用 `Future::poll`来完成的. 47 | 48 | ### 实现 `Future` (Implementing `Future`) 49 | 50 | 让我们来实现一个非常简单的future. 它有以下几个特点: 51 | 52 | 1. 等待到一个特定的时间点. 53 | 2. 输出一些文本到STDOUT. 54 | 3. 产生一个String. 55 | 56 | ```rust 57 | use std::future::Future; 58 | use std::pin::Pin; 59 | use std::task::{Context, Poll}; 60 | use std::time::{Duration, Instant}; 61 | 62 | struct Delay { 63 | when: Instant, 64 | } 65 | 66 | impl Future for Delay { 67 | type Output = &'static str; 68 | 69 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) 70 | -> Poll<&'static str> 71 | { 72 | if Instant::now() >= self.when { 73 | println!("Hello world"); 74 | Poll::Ready("done") 75 | } else { 76 | // 现在忽略这一行 77 | cx.waker().wake_by_ref(); 78 | Poll::Pending 79 | } 80 | } 81 | } 82 | 83 | #[tokio::main] 84 | async fn main() { 85 | let when = Instant::now() + Duration::from_millis(10); 86 | let future = Delay { when }; 87 | 88 | let out = future.await; 89 | assert_eq!(out, "done"); 90 | } 91 | ``` 92 | 93 | ### Async fn as a Future 94 | 95 | 在main函数中,我们实例化一个future并在它上面调用 `.await`. 在异步函数中,我们可以在任何实现了 `Future` 的值上调用 `.await` . 96 | 反过来说, 调用一个 `async` 函数会返回一个实现了 `Future` 的匿名类型. 在 `async fn main()` 中,生成的future大致为: 97 | 98 | ```rust 99 | use std::future::Future; 100 | use std::pin::Pin; 101 | use std::task::{Context, Poll}; 102 | use std::time::{Duration, Instant}; 103 | 104 | enum MainFuture { 105 | // 初始化时,从未轮询过 106 | State0, 107 | // 等待 `延迟` , 比如. `future.await` 这一行. 108 | State1(Delay), 109 | // future已经完成. 110 | Terminated, 111 | } 112 | 113 | impl Future for MainFuture { 114 | type Output = (); 115 | 116 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) 117 | -> Poll<()> 118 | { 119 | use MainFuture::*; 120 | 121 | loop { 122 | match *self { 123 | State0 => { 124 | let when = Instant::now() + 125 | Duration::from_millis(10); 126 | let future = Delay { when }; 127 | *self = State1(future); 128 | } 129 | State1(ref mut my_future) => { 130 | match Pin::new(my_future).poll(cx) { 131 | Poll::Ready(out) => { 132 | assert_eq!(out, "done"); 133 | *self = Terminated; 134 | return Poll::Ready(()); 135 | } 136 | Poll::Pending => { 137 | return Poll::Pending; 138 | } 139 | } 140 | } 141 | Terminated => { 142 | panic!("future polled after completion") 143 | } 144 | } 145 | } 146 | } 147 | } 148 | ``` 149 | 150 | Rust的Future是一种**状态机**. 这里 `MainFuture` 代表future可能的状态枚举. future开始于`State0` 状态. 当调用`poll`时, future会尝试尽可能的推进其内部的状态.如果future能够完成,则返回包含异步计算输出的`Poll::Ready`. 151 | 152 | 如果future**不能够**完成, 通常是由于资源不够而等待,这个时候返回`Poll::Pending`. 接收到`Poll::Pending`会向调用者表明future会在将来某个时刻完成,并且调用者应该稍候再次调用`poll`函数. 153 | 154 | 我们还看到future由其它future组合. 在外部future上调用`poll`会导致在内部future上调用`poll`函数. 155 | 156 | ## 执行器(Executors) 157 | 158 | 异步Rust函数返回future. 必须在Future上调用`poll`来推进其状态. Future可以被其它Future组合. 因此,问题来了,调用最外部的future的`poll`意味着什么? 159 | 160 | 回想一下,要运行异步函数,必须将它们传递给`tokio::spawn`或者使用`#[tokio::main]`注解main函数. 这样的结果是生成的外部future提交给Tokio的执行器.执行器负责在外部Future上调用`Future::poll`,来驱动异步计算的完成. 161 | 162 | ### Mini Tokio 163 | 164 | 为了更好的理解这一切是如何融合的,让我们实现自己的迷你版本的Tokio!完整的代码在 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/mini-tokio/src/main.rs) . 165 | 166 | ```rust 167 | use std::collections::VecDeque; 168 | use std::future::Future; 169 | use std::pin::Pin; 170 | use std::task::{Context, Poll}; 171 | use std::time::{Duration, Instant}; 172 | use futures::task; 173 | 174 | fn main() { 175 | let mut mini_tokio = MiniTokio::new(); 176 | 177 | mini_tokio.spawn(async { 178 | let when = Instant::now() + Duration::from_millis(10); 179 | let future = Delay { when }; 180 | 181 | let out = future.await; 182 | assert_eq!(out, "done"); 183 | }); 184 | 185 | mini_tokio.run(); 186 | } 187 | 188 | struct MiniTokio { 189 | tasks: VecDeque, 190 | } 191 | 192 | type Task = Pin + Send>>; 193 | 194 | impl MiniTokio { 195 | fn new() -> MiniTokio { 196 | MiniTokio { 197 | tasks: VecDeque::new(), 198 | } 199 | } 200 | 201 | /// 在 mini-tokio 实例之上产生一个future 202 | fn spawn(&mut self, future: F) 203 | where 204 | F: Future + Send + 'static, 205 | { 206 | self.tasks.push_back(Box::pin(future)); 207 | } 208 | 209 | fn run(&mut self) { 210 | let waker = task::noop_waker(); 211 | let mut cx = Context::from_waker(&waker); 212 | 213 | while let Some(mut task) = self.tasks.pop_front() { 214 | if task.as_mut().poll(&mut cx).is_pending() { 215 | self.tasks.push_back(task); 216 | } 217 | } 218 | } 219 | } 220 | ``` 221 | 222 | 这将运行异步块. 使用请求延迟来创建一个`Delay`实例并等待它. 然而,我们的实现到目前为止有一个重大的缺陷. 我们的执行器绝不会休眠. 执行器不断 223 | 循环所有产生的future并对其进行轮询. 大多时候,future不准备执行更多的工作,并会返回`Poll::pending`. 这一过程会消耗CPU并且通常没有效率. 224 | 225 | 理想的情况下,我们仅仅想让mini-tokio在future在有进展的时候去轮询future. 当阻塞任务的资源准备好执行请求操作的时候,就会发生这种情况. 如果 226 | 任务想从TCP socket中读取数据,那么我们只想在TCP socket接收到数据时轮询任务. 在我们的方案中,任务在到达指定的`Instant`时被阻塞. 理想情况下 227 | mini-tokio只会在该时间过去后再轮询任务. 228 | 229 | 为了达到这一目的,在对一个资源进行轮询且资源未准备好时,资源转换为就绪状态后将发送一个通知. 230 | 231 | ## 唤醒(Wakers) 232 | 通过该系统(译者注: 指唤醒),资源在通知等待它的任务时表明已经准备就绪,可以继续进行一些其它的操作了. 233 | 234 | 让我们再次看看`Future::poll`的定义: 235 | 236 | ```rust 237 | fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll; 238 | ``` 239 | 240 | `poll`函数中的`Context`参数有一个`waker()`方法. 此方法返回一个绑定到当前任务的[Waker](https://doc.rust-lang.org/std/task/struct.Waker.html) . 241 | `Waker`中又有一个`wake()`方法. 调用这个方法会向执行器发出信息,说明应该安排相关任务的执行计划. 当资源的状态转换到就绪状态时,它们会调用`wake()`方法,来通知执行者轮询任务来推进资源的状态. 242 | 243 | ### 更新`Delay`(Updating `Delay`) 244 | 我们能更新`Delay`来使用唤醒(wakers): 245 | 246 | ```rust 247 | use std::future::Future; 248 | use std::pin::Pin; 249 | use std::task::{Context, Poll}; 250 | use std::time::{Duration, Instant}; 251 | use std::thread; 252 | 253 | struct Delay { 254 | when: Instant, 255 | } 256 | 257 | impl Future for Delay { 258 | type Output = &'static str; 259 | 260 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) 261 | -> Poll<&'static str> 262 | { 263 | if Instant::now() >= self.when { 264 | println!("Hello world"); 265 | Poll::Ready("done") 266 | } else { 267 | // 在当前任务上获取一个waker句柄 268 | let waker = cx.waker().clone(); 269 | let when = self.when; 270 | 271 | // 生产一个定时器线程 272 | thread::spawn(move || { 273 | let now = Instant::now(); 274 | 275 | if now < when { 276 | thread::sleep(when - now); 277 | } 278 | 279 | waker.wake(); 280 | }); 281 | 282 | Poll::Pending 283 | } 284 | } 285 | } 286 | ``` 287 | 288 | 现在,一旦请求的持续时间过去后,调用任务就会得到通知,执行器可以确保再次安排任务. 下一步就是更新mini-tokio来监听唤醒通知. 289 | 290 | 我们的`Delay`实现仍然有一些其它的问题. 我们将在后面修复它. 291 | 292 | ```text 293 | 当一个future返回 Poll::Pending时,它必须确保waker能在某个时刻发出信息. 忘记此操作的结果就是任务会无限的挂起. 294 | 返回 Poll::Pending后忘记唤醒任务是常见bug的来源. 295 | ``` 296 | 297 | 回忆一下`Delay`的第一个迭代版本. 下面是future的实现: 298 | 299 | ```rust 300 | impl Future for Delay { 301 | type Output = &'static str; 302 | 303 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> { 304 | if Instant::now() >= self.when { 305 | println!("Hello world"); 306 | Poll::Ready("done") 307 | }else { 308 | cx.waker().wake_by_ref(); 309 | Poll::Pending 310 | } 311 | } 312 | } 313 | ``` 314 | 315 | 在返回`Poll::Pending`之前,我们调用了`cx.waker().wake_by_ref()`. 这是为了满足future的组合操作. 通过返回`Poll::Pending`,我们负责 316 | 发信号给waker. 因为我们没有实现计时器(timer)线程,所以我们向唤醒程序(waker)发送了内联信息. 这样做的结果是为了future能重新被调度,再次执行, 317 | 并且可能还没有完全准备好. 318 | 319 | 请注意,你可以向waker发送更多的不是必须的信号. 在这种特殊的情况下,即使我们没有准备好继续操作,我们也会向waker发出信号. 除了浪费一个CPU时钟周期外,并没有什么问题. 但是,这种特殊的实现将导致非常繁忙的循环. 320 | 321 | ### 更新Mini-Tokio(Updating Mini-Tokio) 322 | 接下来就是更新Mini Tokio 来接收waker的通知. 我们想让执行器在仅当任务被唤醒时才运行它们,为了做到这一点,Mini Tokio将提供自己的waker. 323 | 当waker被调用时,与它相关的任务会被排队执行. Mini Tokio在轮询future时将waker传递给future. 324 | 325 | 更新后的Mini Tokio将使用channel来存储计划任务. 通道(Channel)允许任务以队列的方式从任意线程执行. Wakers必须是 `Send`和`Sync` 类型的, 326 | 因此我们使用 crossbeam 包中的channel,因为标准库中的channel不是`Sync`的. 327 | 328 | `Send` 与 `Sync` 是Rust提供的与并发相关的一种标记trait. Send 类型可以在不同的线程中传递. 大多数类型都是 Send ,但是像 [Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html) 却不是. 可以通过不可变引用并发访问的类型是 Sync. 一个类型是 Send 但不是 Sync ---- 一个很好的例子是 [Cell](https://doc.rust-lang.org/std/cell/struct.Cell.html),可以通过不可变引用对其修改,因此它不能并发的共享访问. 329 | 330 | 更多关于 `Send` 与 `Sync` 的细节可以参考[chapter in the Rust book](https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html). 331 | 332 | 在 `Cargo.toml` 中添加如下依赖: 333 | 334 | ```toml 335 | crossbeam = "0.7" 336 | ``` 337 | 338 | 然后,更新`MiniTokio` 结构体: 339 | 340 | ```rust 341 | use crossbeam::channel; 342 | use std::sync::Arc; 343 | 344 | struct MiniTokio { 345 | scheduled: channel::Receiver>, 346 | sender: channel::Sender>, 347 | } 348 | 349 | struct Task { 350 | // 这一块后面再填写 351 | } 352 | ``` 353 | 354 | Wakers是`Sync`类型的并且它可以被克隆(Clone). 当调用`wake`时,必须安排任务来执行. 为了实现这个,我们使用channel. 当在waker上调用`wake()`时, 355 | 任务被推送到channel的发送方. 我们的`Task`结构体将实现wake的逻辑. 为了做到这一点,它需要包含生成的Future和channel发送方. 356 | 357 | ```rust 358 | use std::sync::{Arc, Mutex}; 359 | 360 | struct Task { 361 | // Mutex能使用任务实现'同步(sync)'效果,在任意时刻仅能有一个线程能够访问future. 362 | // Mutex (在此场景下)不需要非常正确,真实的tokio没有在这里使用Mutex,但是真实的tokio 363 | // 使用了更多行的代码来实现这一点. 364 | future: Mutex + Send>>>, 365 | executor: channel::Sender>, 366 | } 367 | 368 | impl Task { 369 | fn schedule(self: &Arc) { 370 | self.executor.send(self.clone()); 371 | } 372 | } 373 | ``` 374 | 375 | 为了安排任务,`Arc`将会被clone,并将它通过channel发送. 现在,我们需要将`schedule`函数与 [std::task::Waker](https://doc.rust-lang.org/std/task/struct.Waker.html) 挂钩. 376 | 标准库提供了一套低级别的API [manual vtable construction](https://doc.rust-lang.org/std/task/struct.RawWakerVTable.html) 来做这个. 这种策略为实现者提供了最大的灵活性, 377 | 但是需要大量的unsafe(不安全)的样板代码. 取而代之的是,我们可以直接使用[RawWakerVTable](https://doc.rust-lang.org/std/task/struct.RawWakerVTable.html), 378 | 我们使用[futures](https://docs.rs/futures/)包提供的[ArcWake](https://docs.rs/futures/0.3/futures/task/trait.ArcWake.html) 工具. 379 | 这可以使我们能实现一个简单的trait,来将我们的`Task`结构暴露为一个waker. 380 | 381 | 在`Cargo.toml`中添加如下依赖来拉取`futures`. 382 | 383 | ```toml 384 | futures = "0.3" 385 | ``` 386 | 387 | 然后实现[futures::task::ArcWake](https://docs.rs/futures/0.3/futures/task/trait.ArcWake.html) . 388 | 389 | ```rust 390 | use futures::task::ArcWake; 391 | use std::sync::Arc; 392 | 393 | impl ArcWake for Task { 394 | fn wake_by_ref(arc_self: &Arc) { 395 | arc_self.schedule(); 396 | } 397 | } 398 | ``` 399 | 400 | 当上面的计时器(timer)线程调用`waker.wake()`时,任务被发送到channel通道中去. 下一步我们在`MiniTokio::run()`函数中实现接收和执行任务的功能. 401 | 402 | ```rust 403 | impl MiniTokio { 404 | fn run(&self) { 405 | while let Ok(task) = self.scheduled.recv() { 406 | task.poll(); 407 | } 408 | } 409 | 410 | /// 初始化一个新的 mini-tokio 实例. 411 | fn new() -> MiniTokio { 412 | let (sender, scheduled) = channel::unbounded(); 413 | 414 | MiniTokio { scheduled, sender } 415 | } 416 | 417 | /// 在 mini-tokio 实例上产生一个 future 418 | /// 419 | /// 给future包装task并推其推送到 `scheduled` 队列中. 420 | fn spawn(&self, future: F) 421 | where 422 | F: Future + Send + 'static, 423 | { 424 | Task::spawn(future, &self.sender); 425 | } 426 | } 427 | 428 | impl Task { 429 | fn poll(self: Arc) { 430 | // 从task实例上创建一个waker. 它使用 ArcWake 431 | let waker = task::waker(self.clone()); 432 | let mut cx = Context::from_waker(&waker); 433 | 434 | // 没有其它线程试图锁住future 435 | let mut future = self.future.try_lock().unwrap(); 436 | 437 | // 轮询future 438 | let _ = future.as_mut().poll(&mut cx); 439 | } 440 | 441 | // 使用指定的future产生一个新的task. 442 | // 443 | // 初始化一个新的包含了指定future的task,并将其它推送给 sender. channel另外一半的receiver将接收到它并执行. 444 | fn spawn(future: F, sender: &channel::Sender>) 445 | where 446 | F: Future + Send + 'static, 447 | { 448 | let task = Arc::new(Task { 449 | future: Mutex::new(Box::pin(future)), 450 | executor: sender.clone(), 451 | }); 452 | 453 | let _ = sender.send(task); 454 | } 455 | 456 | } 457 | ``` 458 | 459 | 这里发生了多件事. 首先,实现了`MiniTokio::run()`. 这个函数循环运行,从通道中接收计划任务. 当任务被唤醒时,任务被推送到channel中,这些 460 | 任务在执行时能够取得进展(译者注: 指poll后任务本身的状态能得到推进). 461 | 462 | 另外,`MiniTokio::new()`与`MiniTokio::spawn()`函数也使用channel来调整了一下,而不是使用`VecDeque`. 当一个新的任务产生时,为它们分配 463 | channel 发送部分的副本,任务可以在运行时使用该副本来调度本身. 464 | 465 | `Task::poll()` 函数使用来自`futures`包中的`ArcWake`工具创建一个waker. 此waker用来创建一个`task::Context`. `task::Context`传递给`poll`. 466 | 467 | ## 概要(Summary) 468 | 我们现在已经看到了异步Rust的端到端原理示例. Rust的`async/await` 特性背后由trait支持. 这就允许使用第三方包,像tokio来提供执行细节. 469 | 470 | * Rust的异步操作是惰性的,需要调用者对其进行轮询. 471 | * Wakers被传递给future,以将future与调用它的任务联系起来. 472 | * 当一个资源没有准备好完成时,`Poll::Pending`被返回并记录任务的唤醒程序(waker). 473 | * 当一个资源变为就绪状态时,就会通知任务的唤醒程序(waker). 474 | * 执行器接收到通知并安排任务来执行. 475 | * 任务再一次被轮询,这一次资源是就绪状态并且任务能够取得进展. 476 | 477 | ## 一些零碎的结论(A few loose ends) 478 | 回顾一下,当我们实现`Delay`时,我们说过还要更多的问题要修复. Rust的异步模型允许单个future在执行时跨任务移动. 考虑一下如下代码: 479 | 480 | ```rust 481 | use futures::future::poll_fn; 482 | use std::future::Future; 483 | use std::pin::Pin; 484 | 485 | #[tokio::main] 486 | async fn main() { 487 | let when = Instant::now() + Duration::from_millis(10); 488 | let mut delay = Some(Delay { when }); 489 | 490 | poll_fn(move |cx| { 491 | let mut delay = delay.take().unwrap(); 492 | let res = Pin::new(&mut delay).poll(cx); 493 | assert!(res.is_pending()); 494 | tokio::spawn(async move { 495 | delay.await; 496 | }); 497 | 498 | Poll::Ready(()) 499 | }).await; 500 | } 501 | ``` 502 | 503 | `poll_fn` 函数使用闭包来创建一个`Future`实例. 上面的代码片段创建了一个`Delay`实例,并将其轮询一次,然后将`Delay`实例发送给一个新的任务, 504 | 再等待它. 在这个示例中,使用不同的`Waker`实例多次调用`Delay::poll`. 我们早期的实现中无法处理这种情况,并且由于通知了错误的任务,因此产生的 505 | 任务会永远处于休眠状态. 506 | 507 | 为了修复我们早期的实现,我们可以像下面这样做: 508 | 509 | ```rust 510 | use std::future::Future; 511 | use std::pin::Pin; 512 | use std::sync::{Arc, Mutex}; 513 | use std::task::{Context, Poll, Waker}; 514 | use std::thread; 515 | use std::time::{Duration, Instant}; 516 | 517 | struct Delay { 518 | when: Instant, 519 | waker: Option>>, 520 | } 521 | 522 | impl Future for Delay { 523 | type Output = (); 524 | 525 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { 526 | // 首时,如果第一次future被调用,产生一个计时器线程 527 | // 如果计时器线程已经在运行了,要确保存储的 waker能匹配上当前任务的 waker 528 | if let Some(waker) = &self.waker { 529 | let mut waker = waker.lock().unwrap(); 530 | 531 | // 检查存储的waker能否匹配上当前任务的waker 532 | // 这是必须的,因为 Delay future实例可能在调用poll时移动在不同的task中去 533 | // 如果发生了这种情况, 给定的“Context”中包含的waker将有所不同,我们必须要更新存储的waker以反映此更改. 534 | if !waker.will_wake(cx.waker()) { 535 | *waker = cx.waker().clone(); 536 | } 537 | } else { 538 | let when = self.when; 539 | let waker = Arc::new(Mutex::new(cx.waker().clone())); 540 | self.waker = Some(waker.clone()); 541 | 542 | // 这是第一次 poll 被调用时产生一个计时器线程 543 | thread::spawn(move || { 544 | let now = Instant::now(); 545 | 546 | if now < when { 547 | thread::sleep(when - now); 548 | } 549 | 550 | // 持续时间过去后,通过激活waker来通知调用者. 551 | let waker = waker.lock().unwrap(); 552 | waker.wake_by_ref(); 553 | }); 554 | } 555 | 556 | // 一旦waker被存储且计时器已经开始,就是检查delay是否完成的时候了. 557 | // 通过检查当前时刻来完成. 558 | // 559 | // 如果持续时间过了后, future已经完成 Poll::Ready就会返回 560 | if Instant::now() >= self.when { 561 | Poll::Ready(()) 562 | } else { 563 | // 持续时间没有过去,future没有完成就返回 PollPending 564 | // 565 | // Future trait 要求当返回 Pending 时,future将确保一旦再次对future进行轮询,就会发出指定唤醒信息. 566 | // 567 | // 在我们的例子中,通过这里返回的 Pending 我们可以保证一旦请求的持续时间过去后,我们将调用包含在 Context 参数中的指定waker 568 | // 我们通过产生一个计时器线程来确保这一点. 569 | // 570 | // 如果我们忘记激活waker,任务将会无限的持起. 571 | Poll::Pending 572 | } 573 | } 574 | } 575 | ``` 576 | 577 | 它涉及到一点,但是这个想法是,在每次轮询时,future都会检查所提供的waker是否与先前记录的waker相匹配. 如果两个waker匹配,则什么也不发生. 578 | 如果它们不匹配,则原来记录的waker必须被更新. 579 | 580 | ### `Notify` **utility** 581 | 我们演示了如何使用waker手动实现`Delay` future. Wakers是异步Rust能工作的基础. 通常,不需要降低到该级别. 比如说,在`Delay`的案例中, 582 | 我们可以使用[tokio::sync::Notify](https://docs.rs/tokio/0.3/tokio/sync/struct.Notify.html) 工具完全使用`async/await`来实现它. 583 | 这个实用工具提供了基础的任务通知机制. 它处理了waker的一些细节,包括确保记录的waker与当前任务的waker匹配. 584 | 585 | 使用[Notify](https://docs.rs/tokio/0.3/tokio/sync/struct.Notify.html),我们可以像下面这样,使用 `async/await` 实现`Delay`功能: 586 | ```rust 587 | use tokio::sync::Notify; 588 | use std::sync::Arc; 589 | use std::time::{Duration, Instant}; 590 | use std::thread; 591 | 592 | async fn delay(dur: Duration) { 593 | let when = Instant::now() + dur; 594 | let notify = Arc::new(Notify::new()); 595 | let notify2 = notify.clone(); 596 | 597 | thread::spawn(move || { 598 | let now = Instant::now(); 599 | 600 | if now < when { 601 | thread::sleep(when - now); 602 | } 603 | 604 | notify2.notify_one(); 605 | }); 606 | 607 | 608 | notify.notified().await; 609 | } 610 | ``` 611 | 612 | 613 | ← [Framing](Framing.md) 614 | 615 | → [Select](Select.md) 616 | -------------------------------------------------------------------------------- /doc/BridgingWithSyncCode.md: -------------------------------------------------------------------------------- 1 | ## 使用同步代码桥接(Bridging with sync code) 2 | 在大多数使用 `Tokio` 的示例中,我们使用 `#[tokio::main]` 来标记 `main` 函数,并使得整个工程是异步的。 3 | 然而并不是所有项目都需要这样。比方说,GUI类的应用可能希望在main线程上运行GUI代码,在另外一个线程上运行`tokio` 4 | 的运行时。 5 | 6 | 这一页将告诉你如何使用 `async/await` 来隔离项目中的一小部分。 7 | 8 | ### `#[tokio::main]` 指什么? (Waht `#[tokio::main]` expands to) 9 | `#[tokio::main]` 是一个宏,是一个用来替代调用非异步代码 `main` 函数的宏,并启动一个运行时。(有点绕,自行组织了下好理解点)。比如像下面这样: 10 | 11 | ```rust 12 | #[tokio::main] 13 | async fn main() { 14 | println!("hello world!"); 15 | } 16 | ``` 17 | 18 | 它可以转换成如下写法: 19 | 20 | ```rust 21 | fn main() { 22 | tokio::runtime::Builder::new_multi_thread() 23 | .enable_all() 24 | .build() 25 | .unwrap() 26 | .block_on(async { 27 | println!("Hello world"); 28 | }) 29 | } 30 | ``` 31 | 32 | 通过宏,为了在我们自己的项目中使用 `async/await` , 我们可以做一些类似的事,利用 `block_on` 方法在适当的地方进入异步上下文。 33 | 34 | ### mini-redis的同步接口(A synchronous interface to mini-redis) 35 | 36 | 在这一章节中,我们将介绍如何通过存储 `Runtime` 对象并使用它的 `block_on` 方法来构建与 `mini-redis` 同步的接口。在下面的章节中我们将讨论 37 | 一些替代方法和如何使用这些替代方法。 38 | 39 | 我们要包装的接口是一个异步的 [Client](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html) 类型。它有几个方法,我们将 40 | 实现这几个方法的阻塞版本: 41 | 42 | * [Client::get](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.get) 43 | * [Client::set](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.set) 44 | * [Client::set_expires](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.set_expires) 45 | * [Client::publish](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.publish) 46 | * [Client::subscribe](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.subscribe) 47 | 48 | 为了做到这一点,我们引入一个 `src/blocking_client.rs` 文件,并使用异步 `Client` 类型的包装结构对其进行初始化。 49 | 50 | ```rust 51 | use tokio::net::ToSocketAddrs; 52 | use tokio::runtime::Runtime; 53 | 54 | pub use crate::client::Message; 55 | 56 | /// 与Redis server 建立链接 57 | pub struct BlockingClient { 58 | /// The asynchronous `Client`. 59 | inner: crate::client::Client, 60 | 61 | /// A `current_thread` runtime for executing operations on the 62 | /// asynchronous client in a blocking manner. 63 | /// 一个 `current_thread` 运行时用来在异步 client 上执行阻塞操作 64 | rt: Runtime, 65 | } 66 | 67 | pub fn connect(addr: T) -> crate::Result { 68 | let rt = tokio::runtime::Builder::new_current_thread() 69 | .enable_all() 70 | .build()?; 71 | 72 | // Call the asynchronous connect method using the runtime. 73 | // 使用rt(实际上是tokio的异步运行时)来进行异步connect 74 | let inner = rt.block_on(crate::client::connect(addr))?; 75 | 76 | Ok(BlockingClient { inner, rt }) 77 | } 78 | ``` 79 | 80 | 这里,我们在构造函数中展示了如何在非异步上下文中执行异步方法的示例。我们在 `tokio` 的异步运行时 [Runtime](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html) 81 | 类型上使用 [block_on](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.block_on) 方法,它执行一个异步方法并返回结果。 82 | 83 | 84 | 有一个很重要的细节是这里使用了 [current_thread](https://docs.rs/tokio/1/tokio/runtime/struct.Builder.html#method.new_current_thread) 运行时。 85 | 通常,当我们使用 Tokio 时默认情况下使用使用 [multi_thread](https://docs.rs/tokio/1/tokio/runtime/struct.Builder.html#method.new_multi_thread) 运行时, 86 | 它会产生一堆的后台线程因此它可以在同一时刻非常高效的运行很多东西。在我们的示例中,我们在同一时候仅仅只做一件事,因此我们没必要在后台运行多个线程。这使得 87 | [current_thread](https://docs.rs/tokio/1/tokio/runtime/struct.Builder.html#method.new_current_thread) 非常适合,而不是产生多个线程。 88 | 89 | 调用 [enable_all](https://docs.rs/tokio/1/tokio/runtime/struct.Builder.html#method.enable_all) 在tokio的运行时上来启动IO和计时驱动。 90 | 如果它没被启动,运行时将不能执行IO或计时器功能。 91 | 92 | ```text 93 | 因为 `current_thread` 运行时不产生线程,它仅仅在 `block_on` 被调用时运行。一旦 `block_on` 返回,所有在运行时上产生的任务都会被冻结,直到你 94 | 再次调用 `block_on` 方法。 如果想要在不调用 `block_on` 时产生的任务也要保持运行,那么请使用 `multi_thread` 运行时。 95 | ``` 96 | 97 | 一旦我们有了这样的结构,大部分方法实现起来就很容易了: 98 | 99 | ```rust 100 | use bytes::Bytes; 101 | use std::time::Duration; 102 | 103 | impl BlockingClient { 104 | pub fn get(&mut self, key: &str) -> crate::Result> { 105 | self.rt.block_on(self.inner.get(key)) 106 | } 107 | 108 | pub fn set(&mut self, key: &str, value: Bytes) -> crate::Result<()> { 109 | self.rt.block_on(self.inner.set(key, value)) 110 | } 111 | 112 | pub fn set_expires( 113 | &mut self, 114 | key: &str, 115 | value: Bytes, 116 | expiration: Duration, 117 | ) -> crate::Result<()> { 118 | self.rt.block_on(self.inner.set_expires(key, value, expiration)) 119 | } 120 | 121 | pub fn publish(&mut self, channel: &str, message: Bytes) -> crate::Result { 122 | self.rt.block_on(self.inner.publish(channel, message)) 123 | } 124 | } 125 | ``` 126 | 127 | [Client::subscribe](https://docs.rs/mini-redis/0.4/mini_redis/client/struct.Client.html#method.subscribe) 方法更加有趣, 128 | 因为它将 `Client` 对象转换成 `Subscriber` 对象。 我们可以像下面这样实现它: 129 | 130 | ```rust 131 | /// 一个能进入的 发布/订阅模式的客户端 132 | /// 133 | /// Once clients subscribe to a channel, they may only perform 134 | /// 一旦有客户端订阅一个通道,它们仅能执行 pub/sub 相关的命令。 135 | /// pub/sub related commands. The `BlockingClient` type is 136 | /// `BlockingClient` 类型被转换成一个 `BlockingSubscriber` 类型是为了防止非 pub/sub 方法被调用。 137 | /// transitioned to a `BlockingSubscriber` type in order to 138 | /// prevent non-pub/sub methods from being called. 139 | pub struct BlockingSubscriber { 140 | /// The asynchronous `Subscriber`. 141 | /// 异步 `Subscriber` 142 | inner: crate::client::Subscriber, 143 | 144 | /// A `current_thread` runtime for executing operations on the 145 | /// asynchronous client in a blocking manner. 146 | /// `current_thread` 运行时用于以阻塞的方式来运行异步client. 147 | rt: Runtime, 148 | } 149 | 150 | impl BlockingClient { 151 | pub fn subscribe(self, channels: Vec) -> crate::Result { 152 | let subscriber = self.rt.block_on(self.inner.subscribe(channels))?; 153 | Ok(BlockingSubscriber { 154 | inner: subscriber, 155 | rt: self.rt, 156 | }) 157 | } 158 | } 159 | 160 | impl BlockingSubscriber { 161 | pub fn get_subscribed(&self) -> &[String] { 162 | self.inner.get_subscribed() 163 | } 164 | 165 | pub fn next_message(&mut self) -> crate::Result> { 166 | self.rt.block_on(self.inner.next_message()) 167 | } 168 | 169 | pub fn subscribe(&mut self, channels: &[String]) -> crate::Result<()> { 170 | self.rt.block_on(self.inner.subscribe(channels)) 171 | } 172 | 173 | pub fn unsubscribe(&mut self, channels: &[String]) -> crate::Result<()> { 174 | self.rt.block_on(self.inner.unsubscribe(channels)) 175 | } 176 | } 177 | ``` 178 | 179 | 因此,`subscribe` 方法会首先使用运行时将异步的 `Client` 转换成异步的 `Subscriber` 。 然后它将生成的 `Subscriber`与 `Runtime` 一起存储 180 | ,并使用 [block_on](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.block_on) 来实现各种方法。 181 | 182 | 注意到,异步的 `Subscriber` 结构体有一个非异步的方法 `get_subscribed` 。为了处理这个,我们直接使用非运行时的方式来调用它。 183 | 184 | ### 其它方法(Other approaches) 185 | 上面的章节解释了实现同步包装器的简单方式,但这不是唯一的方法。一般的方法还有: 186 | 187 | * 创建一个 [Runtime](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html) 并在异步代码上调用 [block_on](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.block_on) 188 | * 创建一个 [Runtime](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html) 并在它上面 [Spawn](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.spawn) 一些事。 189 | * 在一个分隔的线程上运行一个 `Runtime` 并给它发消息。 190 | 191 | 我们已经看到了第一种的实现方式,另外两种将在下面来介绍。 192 | 193 | 194 | #### 在一个Runtime上产生一些东西 (Spawning things on a runtime) 195 | [Runtime](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html) 对象上有一个 [spawn](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.spawn) 方法。 196 | 当我们调用这个方法时,你可以在运行时上产生一个新任务。比如像下面这样: 197 | 198 | ```rust 199 | use tokio::runtime::Builder; 200 | use tokio::time::{sleep, Duration}; 201 | 202 | fn main() { 203 | let runtime = Builder::new_multi_thread() 204 | .worker_threads(1) 205 | .enable_all() 206 | .build() 207 | .unwrap(); 208 | 209 | let mut handles = Vec::with_capacity(10); 210 | for i in 0..10 { 211 | handles.push(runtime.spawn(my_bg_task(i))); 212 | } 213 | 214 | // Do something time-consuming while the background tasks execute. 215 | // 当后台任务执行时做一些事来消耗下时间 216 | std::thread::sleep(Duration::from_millis(750)); 217 | println!("Finished time-consuming task."); 218 | 219 | // Wait for all of them to complete. 220 | // 等待所有任务完成 221 | for handle in handles { 222 | // The `spawn` method returns a `JoinHandle`. A `JoinHandle` is 223 | // a future, so we can wait for it using `block_on`. 224 | 225 | // spawn 方法返回一个 JoinHandle. 它是一个 future, 因此我们可以在它上面使用 block_on 226 | runtime.block_on(handle).unwrap(); 227 | } 228 | } 229 | 230 | async fn my_bg_task(i: u64) { 231 | // By subtracting, the tasks with larger values of i sleep for a 232 | // shorter duration. 233 | 234 | // 通过相减,较大值的任务 sleep 时间更短 235 | let millis = 1000 - 50 * i; 236 | println!("Task {} sleeping for {} ms.", i, millis); 237 | 238 | sleep(Duration::from_millis(millis)).await; 239 | 240 | println!("Task {} stopping.", i); 241 | } 242 | ``` 243 | 244 | ```text 245 | Task 0 sleeping for 1000 ms. 246 | Task 1 sleeping for 950 ms. 247 | Task 2 sleeping for 900 ms. 248 | Task 3 sleeping for 850 ms. 249 | Task 4 sleeping for 800 ms. 250 | Task 5 sleeping for 750 ms. 251 | Task 6 sleeping for 700 ms. 252 | Task 7 sleeping for 650 ms. 253 | Task 8 sleeping for 600 ms. 254 | Task 9 sleeping for 550 ms. 255 | Task 9 stopping. 256 | Task 8 stopping. 257 | Task 7 stopping. 258 | Task 6 stopping. 259 | Finished time-consuming task. 260 | Task 5 stopping. 261 | Task 4 stopping. 262 | Task 3 stopping. 263 | Task 2 stopping. 264 | Task 1 stopping. 265 | Task 0 stopping. 266 | ``` 267 | 268 | 在上面的示例中,我们在运行时上产生了10个后台任务,并等待所有任务完成。比如,这可能是在图形应用程序中实现后台联网的好方法,因为网络请求太耗时间,因而 269 | 无法在main gui 线程上运行它们。相反,你可以在后台运行 tokio 运行时来生成网络请求,并在请求完成将任务信息发送回GUI线程代码,如果你想要进度条(效果) 270 | ,甚至可以增量发送。 271 | 272 | 在这个例子中,运行时配置 [multi_thread](https://docs.rs/tokio/1/tokio/runtime/struct.Builder.html#method.new_multi_thread) 是很重要的。 273 | 如果你将它改为 `current_thread` 运行时,你会发现耗时的任务会在任何后台任务开始之前完成。这是因为在 `current_thread` 上产生的后台任务,只会在调用 274 | `block_on` 期间运行,否则运行时没有任何地方可以运行它们。 275 | 276 | 例子,通过调用 [spawn](https://docs.rs/tokio/1/tokio/runtime/struct.Runtime.html#method.spawn) 返回的 [JoinHandle](https://docs.rs/tokio/1/tokio/task/struct.JoinHandle.html) 277 | 对象上的 `block_on` 方法来等待生成任务的完成,但这也并非唯一方法。这里还有一些其它的替代方案: 278 | 279 | * 使用消传递通道,比如: [tokio::sync::mpsc](https://docs.rs/tokio/1/tokio/sync/mpsc/index.html) 。 280 | * 修改一个受保护的值,比如 `Mutex` 对于GUI中的进度条来说,这会是一个很好的方法,其中GUI的每一帧读取共享值。 281 | 282 | `spawn` 方法也可用于 [Handle](https://docs.rs/tokio/1/tokio/runtime/struct.Handle.html) 类型。可以clone `handle` 类型来获得运行时的多个句柄, 283 | 每一个 `handle` 可被用于在运行时上产生新的任务。 284 | 285 | #### 发送消息(Sending messages) 286 | 第三种技术是生成一个运行时(Runtime)并使用消息传递与其通信。它是一种最灵活的方式,你可以在下面找到一个基本的使用示例: 287 | 288 | ```rust 289 | se tokio::runtime::Builder; 290 | use tokio::sync::mpsc; 291 | 292 | pub struct Task { 293 | name: String, 294 | // info that describes the task 295 | } 296 | 297 | async fn handle_task(task: Task) { 298 | println!("Got task {}", task.name); 299 | } 300 | 301 | #[derive(Clone)] 302 | pub struct TaskSpawner { 303 | spawn: mpsc::Sender, 304 | } 305 | 306 | impl TaskSpawner { 307 | pub fn new() -> TaskSpawner { 308 | // Set up a channel for communicating. 309 | // 设置一个用于沟通的 channel 310 | let (send, mut recv) = mpsc::channel(16); 311 | 312 | // Build the runtime for the new thread. 313 | // 314 | // The runtime is created before spawning the thread 315 | // to more cleanly forward errors if the `unwrap()` 316 | // panics. 317 | // 为新线程构造一个 运行时(runtime) 318 | // 运行时在 线程之前创建出来可以更清楚的来传递错误,如果使用了 unwrap() panics 的话。 319 | let rt = Builder::new_current_thread() 320 | .enable_all() 321 | .build() 322 | .unwrap(); 323 | 324 | std::thread::spawn(move || { 325 | rt.block_on(async move { 326 | while let Some(task) = recv.recv().await { 327 | tokio::spawn(handle_task(task)); 328 | } 329 | 330 | // Once all senders have gone out of scope, 331 | // the `.recv()` call returns None and it will 332 | // exit from the while loop and shut down the 333 | // thread. 334 | // 一旦所有的 sender 超出作用域时,`.recv()` 的调用会返回None, 它将退出 while 循环并关闭线程 335 | }); 336 | }); 337 | 338 | TaskSpawner { 339 | spawn: send, 340 | } 341 | } 342 | 343 | pub fn spawn_task(&self, task: Task) { 344 | match self.spawn.blocking_send(task) { 345 | Ok(()) => {}, 346 | Err(_) => panic!("The shared runtime has shut down."), 347 | } 348 | } 349 | } 350 | ``` 351 | 352 | 这个示例可以通过多种方式来配置。比如,你可以使用 [Semaphore](https://docs.rs/tokio/1/tokio/sync/struct.Semaphore.html) 信号量来限制活动的任务数量, 353 | 或者你可以使用相反方向的channel向 spawner 发送响应。当你以这种方式生成运行时时, 它是一个 [actor](https://ryhl.io/blog/actors-with-tokio/) 类型。 354 | 355 | 356 | 357 | ← [主题](Topics.md) 358 | 359 | → [优雅关机](GracefulShutdown.md) -------------------------------------------------------------------------------- /doc/Channels.md: -------------------------------------------------------------------------------- 1 | ## 通道(Channels) 2 | 现在我们已经学习了一些与Tokio相关的并发知识, 让我们将这些知识应用到客户端. 假设我们想运行两个并发的Redis命令. 我们可以为每一个命令产生 3 | 一个任务来处理. 然后这两个命令将同时发生. 4 | 5 | 首写我们可能尝试写像下面这样的代码: 6 | 7 | ```rust 8 | use mini_redis::client; 9 | 10 | #[tokio::main] 11 | async fn main() { 12 | // 建立一个与Server的链接 13 | let mut client = client::connect("127.0.0.1:6379").await.unwrap(); 14 | 15 | // 产生两个任务, 一个获取key, 另外一个设置key值. 16 | let t1 = tokio::spawn(async { 17 | let res = client.get("hello").await; 18 | }); 19 | 20 | let t2 = tokio::spawn(async { 21 | client.set("foo", "bar".into()).await; 22 | }); 23 | 24 | t1.await.unwrap(); 25 | t2.await.unwrap(); 26 | } 27 | ``` 28 | 29 | 上面的代码不能被编译, 因为两个任务都需要以某种方式访问 `client` . 而 `client` 没有实现 `Copy` , 因此如果没有一些可以促进"共享"的代码, 它将 30 | 无法编译. 另外, `Client::set` 需要 `&mut self`, 这意味着需要独占的访问权才能调用它. 我们可以为每一个任务打开一个链接,但这不是一个好办法. 31 | 我们不能使用 `std::sync::Mutex` , 因为 `.await` 需要在持有锁的情况下调用. 我们可以使用 `tokio::sync::Mutex` , 但是这样又仅允许一个 32 | 进行中的请求. 如果客户端实现 [pipelining](https://redis.io/topics/pipelining) , 异步互斥锁又不能充分的利用链接了. 33 | 34 | ## 消息传递(Message passing) 35 | 结论就是使用消息传递机制. 该模式涉及产生一个专门的任务来管理 `client` 中的资源. 任何希望发出请求的任务都会向`client` 的任务发送一条消息. 36 | `client` 任务代表发送方发出请求, 并将响应返回给发送方. 37 | 38 | 使用这种策略,可以建立单个的链接. 管理 `client` 的任务可以获取独占访问权, 以便来调用 `get` 和 `set` . 另外, 通道还用作缓冲区. 39 | 客户端任务比较繁忙的时候,可能会将操作发送到客户端任务. 一旦 `client` 任务可以用来处理新链接, 它将从通道中拉取下一个请求(进行处理). 40 | 这样的方式可以提高吞吐量,并可以扩展的方式来支持链接池. 41 | 42 | ## Tokio的通道原语(Tokio's channel primitives) 43 | Tokio提供了许多通道( [number of channels](https://docs.rs/tokio/0.2/tokio/sync/index.html) ), 每一种都有其对应的用途. 44 | * [mpsc](https://docs.rs/tokio/0.2/tokio/sync/mpsc/index.html) : 多生产者(multi-producer)单消费者(single-consumer)通道. 可以发送许多的值. 45 | * [oneshot](https://docs.rs/tokio/0.2/tokio/sync/oneshot/index.html) : 单生产者(single-producer)单消费者(single-consumer)通道. 可以发送单个值. 46 | * [broadcast](https://docs.rs/tokio/0.2/tokio/sync/broadcast/index.html) : 多生产者多消费者(广播). 可以发送许多值,每一个接收者都能看到每一个值. 47 | * [watch](https://docs.rs/tokio/0.2/tokio/sync/watch/index.html) : 单生产者多消费者. 可以发送许多值,但是不会保留历史记录. 接收者仅能看到最新的值. 48 | 49 | 如果你需要一个多生产者多消费者通道且仅仅只想让一个消费者看到所有消息, 你可以使用 [async-channel](https://docs.rs/async-channel/) 包. 50 | 在异步Rust之外还有其它通道可以使用,比如, [std::sync::mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) 和 [crossbeam::channel](https://docs.rs/crossbeam/latest/crossbeam/channel/index.html) . 这些通道通过阻塞线程来等待消息, 这在 51 | 异步代码中是不允许的. 52 | 53 | 在本章节中我们将使用 [mpsc](https://docs.rs/tokio/0.2/tokio/sync/mpsc/index.html) 与 [oneshot](https://docs.rs/tokio/0.2/tokio/sync/oneshot/index.html) . 54 | 后面的章节将讨论其它的消息通道类型. 本章完整的代码可以在 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/channels/src/main.rs) 找到. 55 | 56 | ## 定义消息类型(Define the message type) 57 | 在大多数情况下, 使用消息传递时, 接收消息的任务会响应多个命令. 在我们的案例中, 任务将响应 `GET` 与 `SET` 命令. 为了对这个建模,我们首先 58 | 定义一个 `Command` 的枚举, 并为每种命令类型包含一个变体. 59 | 60 | ```rust 61 | use bytes::Bytes; 62 | 63 | #[derive(Debug)] 64 | enum Command { 65 | Get { 66 | key: String, 67 | }, 68 | Set { 69 | key: String, 70 | val: Bytes, 71 | } 72 | } 73 | ``` 74 | 75 | ## 创建通道(Create the channel) 76 | 在 `main` 中 创建 `mpsc` 通道. 77 | 78 | ```rust 79 | use tokio::sync::mpsc; 80 | 81 | #[tokio::main] 82 | async fn main() { 83 | // 创建一个最大容量为32的通道 84 | let (mut tx, mut rx) = mpsc::channel(32); 85 | 86 | // ... 这里先休息一下 87 | } 88 | ``` 89 | 90 | `mpsc` 通道被用来发送一个命令到管理Redis链接的任务中. 多生产者的能力是能让许多的任务发送消息. 创建的通道返回两个值, 一个是发送者(Sender)一个是 91 | 接收者(receiver). 它们两者被分开使用. 他们可能移动到不同的任务中去. 92 | 93 | 被创建的通道容量为32. 如果消息的发送速度大于接收的速度, 通道会储存它们. 一旦通道中存了32条消息时,就会调用 `send(...).await` 进入睡眠状态, 94 | 直到接收者删除一条消息为止.(译者注: 就是说当接收者有能力能再次处理消息时, 睡眠状态才会结束). 95 | 96 | 通过 **克隆** (**cloning**) `Sender` 可以完成多个任务的发送. 比如像下面这样: 97 | 98 | ```rust 99 | use tokio::sync::mpsc; 100 | 101 | #[tokio::main] 102 | async fn main() { 103 | let (tx, mut rx) = mpsc::channel(32); 104 | let tx2 = tx.clone(); 105 | 106 | tokio::spawn(async move { 107 | tx.send("sending from first handle").await; 108 | }); 109 | 110 | tokio::spawn(async move { 111 | tx2.send("sending from second handle").await; 112 | }); 113 | 114 | while let Some(message) = rx.recv().await { 115 | println!("GOT = {}", message); 116 | } 117 | } 118 | ``` 119 | 120 | 两条消息都发送到单个 `Receiver` 处理. 不可能克隆 `mpsc` 通道中的接收者. 121 | 122 | 当每个 `Sender` 超出作用域范围或者被dropped时, 它不能再发送更多的消息到通道中. 此时, `Receiver` 上的 `rev` 调用都将返回 `None` , 123 | 这意味着所有发送者都已经消失且通道已关闭. 124 | 125 | 在我们管理Redis链接的任务中,它知道一旦通道关闭就能关闭Redis链接, 因为该链接不再使用了. 126 | 127 | ## 产生管理任务(Spawn manager task) 128 | 下一步, 产生一个任务来处理来自通道的消息. 首先, 建立与Redis的链接. 然后, 通过Redis链接发出接收到的命令. 129 | 130 | ```rust 131 | use mini_redis::client; 132 | // move 关键字用来移动 rx 所有权到task中去 133 | let manager = tokio::spawn(async move { 134 | // 建立与Server的链接 135 | let mut client = client::connect("127.0.0.1:6379").await.unwrap(); 136 | 137 | // 开始接收消息 138 | while let Some(cmd) = rx.recv().await { 139 | use Command::*; 140 | 141 | match cmd { 142 | Get { key } => { 143 | client.get(&key).await; 144 | } 145 | Set { key, val } => { 146 | client.set(&key, val).await; 147 | } 148 | } 149 | } 150 | }); 151 | ``` 152 | 153 | 现在,更新这两个任务来使用通道发送命令,而不是直接在Redis的链接上发出命令. 154 | 155 | ```rust 156 | // Sender 被移动到task中了, 这里有两个任务, 所以我们需要第二个 Sender 157 | let tx2 = tx.clone(); 158 | 159 | // 产生两个任务一个得到key值,一个设置key的值 160 | let t1 = tokio::spawn(async move { 161 | let cmd = Command::Get { 162 | key: "hello".to_string(), 163 | }; 164 | 165 | tx.send(cmd).await.unwrap(); 166 | }); 167 | 168 | let t2 = tokio::spawn(async move { 169 | let cmd = Command::Set { 170 | key: "foo".to_string(), 171 | val: "bar".into(), 172 | }; 173 | 174 | tx2.send(cmd).await.unwrap(); 175 | }); 176 | ``` 177 | 178 | ## 接收响应 179 | 最后一步就是接收来管理任务的响应. `GET` 命令需要获取值, 而 `SET` 命令需要知道操作是否完成. 180 | 181 | 为了传递响应,可以使用 `oneshot` 通道. `oneshot` 通道是一个经过了优化的单生产者单消费者通道,用来发送单个值. 在我们的案例中,单个值就是响应. 182 | 183 | 与 `mpsc` 类似, `oneshot` 返回一个发送者(Sender)和一个接收者(receiver)处理器. 184 | 185 | ```rust 186 | use tokio::sync::oneshot; 187 | 188 | let (tx,rx) = oneshot::channel(); 189 | ``` 190 | 191 | 与 `mpsc` 不同, `oneshot` 它不能指定任何容量, 因为容量始终为1. 另外, 两个处理器都不能被克隆(译者注: 指 tx, rx). 192 | 193 | 为了接收到来自管理任务的响应, 在发送一个命令之前, 一个 `oneshot` 通道将被创建. 通道 `Sender` 的一半包含在管理任务的命令中. 接收方的一半用来接收响应. 194 | 195 | 首先, 更新 `Command` 来包含一个 `Sender` . 为了方便, 为 `Sender` 定义一个类型别名. 196 | 197 | ```rust 198 | use tokio::sync::oneshot; 199 | use bytes::Bytes; 200 | 201 | /// 多个不同的命令在单个通道上复用. 202 | #[derive(Debug)] 203 | enum Command { 204 | Get { 205 | key: String, 206 | resp: Responder>, 207 | }, 208 | Set { 209 | key: String, 210 | val: Vec, 211 | resp: Responder<()>, 212 | }, 213 | } 214 | 215 | /// 由请求者提供并通过管理任务来发送,再将命令的响应返回给请求者. 216 | type Responder = oneshot::Sender>; 217 | ``` 218 | 219 | 现在,更新发出命令的任务来包括 `oneshot::Sender` . 220 | 221 | ```rust 222 | let t1 = tokio::spawn(async move { 223 | let (resp_tx, resp_rx) = oneshot::channel(); 224 | let cmd = Command::Get { 225 | key: "hello".to_string(), 226 | resp: resp_tx, 227 | }; 228 | 229 | // 发送 GET 请求 230 | tx.send(cmd).await.unwrap(); 231 | 232 | // 等待响应结果 233 | let res = resp_rx.await; 234 | println!("GOT = {:?}", res); 235 | }); 236 | 237 | let t2 = tokio::spawn(async move { 238 | let (resp_tx, resp_rx) = oneshot::channel(); 239 | let cmd = Command::Set { 240 | key: "foo".to_string(), 241 | val: b"bar".to_vec(), 242 | resp: resp_tx, 243 | }; 244 | 245 | // 发送 GET 请求 246 | tx2.send(cmd).await.unwrap(); 247 | 248 | // 等待响应结果 249 | let res = resp_rx.await; 250 | println!("GOT = {:?}", res) 251 | }); 252 | ``` 253 | 254 | 最后, 更新管理任务以通过oneshot通道发送响应. 255 | 256 | ```rust 257 | while let Some(cmd) = rx.recv().await { 258 | match cmd { 259 | Command::Get { key, resp } => { 260 | let res = client.get(&key).await; 261 | // 忽略错误 262 | let _ = resp.send(res); 263 | } 264 | Command::Set { key, val, resp } => { 265 | let res = client.set(&key, val.into()).await; 266 | // 忽略错误 267 | let _ = resp.send(res); 268 | } 269 | } 270 | } 271 | ``` 272 | 273 | 在 `oneshot::Sender` 上调用 `send` 会立即完成而不需要 `.await` 操作. 这是因为在 `oneshot` 通道上的 `send` 总是立即失败或者成功, 274 | 而没有任何等待. 275 | 276 | 当接收一半时删除(dropped)了, 在 `oneshot` 通道上发送一个值会返回 `Err` . 这表明接收方不再对响应有兴趣,在我们的方案中, 接收方的取消操作 277 | 是可以被接受的事件. `resp.send(...)` 返回的 `Err` 不需要处理. 278 | 279 | 你可以在 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/channels/src/main.rs) 找到完整的代码. 280 | 281 | ## 背压与通道边界(Backpressure and bounded channels) 282 | 每当引用并发或队列时, 最重要的是确保队列是有界的, 且系统会优雅的处理负载. 无界队列最终将占用所有的内存,并导致系统以无法预测的方式发生故障. 283 | 284 | Tokio 比较注意避免隐式(无界)队列. 其中很大一部分原因是异步操作是惰性的. 考虑如下代码: 285 | 286 | ```rust 287 | loop { 288 | async_op(); 289 | } 290 | ``` 291 | 292 | 如果异步操作非常急切的运行, 在没有确保先前操作已经完成的情况下, loop 循环将会重复入队一个新的 `async_op` 来运行. 这就导致隐式无界队列的产生. 293 | 基于回调的系统与基于feature系统尤其容易受到这样的影响. 294 | 295 | 然而,使用Tokio和异步Rust, 上面的代码片段根本不会运行 `async_op` . 这是因为你没有调用 `.await` . 如果代码片段更新一下变为使用 `.await` , 296 | 则 loop 循环将在重新开始之前等待上一个操作完成. 297 | 298 | ```rust 299 | loop { 300 | // 不会重复 直到 async_op 操作完成 301 | async_op().await; 302 | } 303 | ``` 304 | 305 | 要明确的引用并发与队列,做到这一点的方法包括: 306 | 307 | * `tokio::spawn` 308 | * `select!` 309 | * `join!` 310 | * `mpsc::channel` 311 | 312 | 当这样做时,请确保一定数量的并发总量. 比如说, 在编写TCP接收循环时, 要确保打开的socket链接总数是有界的. 当使用 `mspc::channel` 时, 要选择 313 | 一个可管理的通道容量(译者注: 就是要设置一个确定的容量数). 特定的界限值将取决于应用程序. 314 | 315 | 注意并选择(或设置)良好的边界是编写可靠Tokio应用的重要组成部分. 316 | 317 | 318 | 319 | ← [共享状态](SharedState.md) 320 | 321 | → [I/O](IO.md) 322 | 323 | -------------------------------------------------------------------------------- /doc/Framing.md: -------------------------------------------------------------------------------- 1 | ## 帧(Framing) 2 | 现在,我们将应用刚刚学到的的I/O知识,并以此来实现Mini-Redis的帧层. 形成帧是获取字节流并将其转换为帧流的过程. 帧是两个对等体之间传输数据的单位. 3 | Redis协议帧像下面这样: 4 | 5 | ```rust 6 | use bytes::Bytes; 7 | 8 | enum Frame { 9 | Simple(String), 10 | Error(String), 11 | Integer(u64), 12 | Bulk(Bytes), 13 | Null, 14 | Array(Vec), 15 | } 16 | ``` 17 | 18 | 注意帧仅由没有任何语义的数据组成. 命令的解析和实现发生在更高的层级. 19 | 20 | 比如说, HTTP的帧可能看起来像下面这样: 21 | 22 | ```rust 23 | enum HttpFrame { 24 | RequestHead { 25 | method: Method, 26 | uri: Uri, 27 | version: Version, 28 | headers: HeaderMap, 29 | }, 30 | ResponseHead { 31 | status: StatusCode, 32 | version: Version, 33 | headers: HeaderMap, 34 | }, 35 | BodyChunk { 36 | chunk: Bytes, 37 | }, 38 | } 39 | ``` 40 | 41 | 为了去实现Mini-Redis的帧, 我们将实现一个`connection`结构体, 该结构体包装了一个`TcpStream`并读取/写入`mini_redis::Frame`的值. 42 | 43 | ```rust 44 | use tokio::net::TcpStream; 45 | use mini_redis::{Frame, Result}; 46 | 47 | struct connection { 48 | stream: TcpStream, 49 | // ... 其它属性字段 50 | } 51 | 52 | impl connection { 53 | /// 从Connection中读取一个帧 54 | /// 55 | /// 如果 EOF 到达则返回 None 56 | pub async fn read_frame(&mut self) 57 | -> Result> 58 | { 59 | // 在这里实现 60 | } 61 | 62 | /// 写入一个帧到链接Connection中 63 | pub async fn write_frame(&mut self, frame: &Frame) 64 | -> Result<()> 65 | { 66 | // 在这里实现 67 | } 68 | } 69 | ``` 70 | 71 | 你能在[这里](https://redis.io/topics/protocol) 找到完整的Redis协议细节. 完整的 `connection` 代码在 [这里](https://github.com/tokio-rs/mini-redis/blob/tutorial/src/connection.rs) . 72 | 73 | ## 缓冲区读取(Buffered reads) 74 | `read_frame` 方法在返回之前会等待接收整个帧. 单次调用`TcpStream::read()`方法可能会返回任意数量的数据. 它可能包含一个完整的帧,一部分帧,或者多个帧. 75 | 如果接收到部分帧,则会被缓存,并从socket套接字中读取更多的数据. 如果接收到多个帧, 则返回第一个帧,并缓冲其它的数据,直到下一次调用`read_frame`为止. 76 | 77 | 为了实现这一点, `connection`需要一个读取缓冲区字段. 数据从socket中读取到读缓冲区(read buffer)中. 当一个帧被解析时, 相应的数据就会从缓冲区中移除. 78 | 79 | 我们将使用 [BytesMut](https://docs.rs/bytes/1/bytes/struct.BytesMut.html) 作为缓冲区(buffer)的类型. 这是一个 [Bytes](https://docs.rs/bytes/1/bytes/struct.Bytes.html) 的可变版本. 80 | 81 | ```rust 82 | use bytes::BytesMut; 83 | use tokio::net::TcpStream; 84 | 85 | pub struct connection { 86 | stream: TcpStream, 87 | buffer: BytesMut, 88 | } 89 | 90 | impl connection { 91 | pub fn new(stream: TcpStream) -> connection { 92 | connection { 93 | stream, 94 | // 默认分配buffer容量为4kb 95 | buffer: BytesMut::with_capacity(4096), 96 | } 97 | } 98 | } 99 | ``` 100 | 101 | 下一步,我们将实现 `read_frame()` 方法. 102 | 103 | ```rust 104 | use tokio::io::AsyncReadExt; 105 | use bytes::Buf; 106 | use mini_redis::Result; 107 | 108 | pub async fn read_frame(&mut self) 109 | -> Result> 110 | { 111 | loop { 112 | // 尝试从buffer数据中解析一个帧. 如果buffer中有足够的数据,那么帧就返回 113 | if let Some(frame) = self.parse_frame()? { 114 | return Ok(Some(frame)); 115 | } 116 | 117 | // 没有足够的数据读取到一个帧中, 那么尝试从socket中读取更多的数据 118 | // 如果成功了, 一定数据的字节被返回. '0' 表明到了流的末尾 119 | if 0 == self.stream.read_buf(&mut self.buffer).await? { 120 | // 远程关闭了链接,为了彻底关闭, 读缓冲区中应该没有数据了. 如果存在数据, 那说明对等方在发送帧时关闭了socket 121 | return if self.buffer.is_empty() { 122 | Ok(None) 123 | } else { 124 | Err("connection reset by peer".into()) 125 | } 126 | } 127 | } 128 | } 129 | ``` 130 | 131 | 让我们分解一下. `read_frame` 方循环运行. 首先, `self.parse_frame()` 方法被调用. 这将尝试从`self.buffer` 中解析一个redis帧. 132 | 如果这里有足够的数据解析成一个帧, 那么就会返回给`read_frame()`调用者一个帧. 否则的话,我们将尝试从socket中读取更多的数据到缓冲区中. 133 | 读取更多数据后,再一次调用`parse_frame()`方法. 这一次, 如果已经接收到足够的数据,那么就能解析成功. 134 | 135 | 当从流(Stream)中读取时,返回值0表示不再从对等方接收数据. 如果读取缓冲区中任然有数据,则表明已经接收到部分帧,并且链接突然终止了. 这种情况是 136 | 一种错误并会返回`Err`. 137 | 138 | ## `Buf` trait 139 | 当从流中读取时, 将调用 `read_buf`方法. 这个版本的read函数采用了一个从 [bytes](https://docs.rs/bytes/) 包中实现了 [BufMut](https://docs.rs/bytes/0.5/bytes/trait.BufMut.html) 的值. 140 | 141 | 首先,考虑如何使用`read()`实现同样的读取循环. 可以使用`Vec`来代替`BytesMut`. 142 | 143 | ```rust 144 | use tokio::net::TcpStream; 145 | 146 | pub struct connection { 147 | stream: TcpStream, 148 | buffer: Vec, 149 | cursor: usize, 150 | } 151 | 152 | impl connection { 153 | pub fn new(stream: TcpStream) -> connection { 154 | connection { 155 | stream, 156 | // 分配4kb的缓冲区容量 157 | buffer: vec![0; 4096], 158 | cursor: 0, 159 | } 160 | } 161 | } 162 | ``` 163 | 164 | `connection`上的`read_frame()` 函数. 165 | 166 | ```rust 167 | use mini_redis::{Frame, Result}; 168 | 169 | pub async fn read_frame(&mut self) -> Result> 170 | { 171 | loop { 172 | if let Some(frame) = self.parse_frame()? { 173 | return Ok(Some(frame)); 174 | } 175 | 176 | // 确保buffer有容量 177 | if self.buffer.len() == self.cursor { 178 | // 增长buffer 179 | self.buffer.resize(self.cursor * 2, 0); 180 | } 181 | 182 | // 读取到缓冲区, 跟踪读取的字节数 183 | let n = self.stream.read( 184 | &mut self.buffer[self.cursor..]).await?; 185 | 186 | if 0 == n { 187 | if self.cursor == 0 { 188 | return Ok(None); 189 | } else { 190 | return Err("connection reset by peer".into()); 191 | } 192 | } else { 193 | // 更新游标 194 | self.cursor += n; 195 | } 196 | } 197 | } 198 | ``` 199 | 200 | 在使用字节数组进行读取时, 我们还必须保持一个游标,来跟踪已经缓冲了多少数据. 我们必须确保缓冲区的空白部分传递给 `read()`. 否则会覆盖缓冲区的数据. 201 | 如果缓冲区被填满, 我们必须增加缓冲区来继续读取. 在`parse_frame()`(但不包括)中, 我们还必须解析`self.buffer[..self.cursor]`包含的数据. 202 | 203 | 因为将字节数据与游标配对非常常见, 所以 `bytes` 包中提供了代表字节数组和游标的抽象. `Buf` trait可以被需要读取数据的类型实现. `BufMut` trait可以被 204 | 需要数据写入的类型实现. 当传递一个 `T:BufMut` 到 `read_buf()`时, 缓冲区的内部游标由`read_buf()`自动更新. 因为这一点,在我们的`read_frame`版本中, 205 | 我们不需要自己来管理自己的游标. 206 | 207 | 另外, 当使用 `Vec` 时缓冲区必须要初始化. `vec![0; 4096]` 分配一个大小为4096字节的数组并在每个位置写0. 当调整buffer的大小时,新的容量也必须要使用0 208 | 来初始化. 初始化的过程不是无消耗的. 当使用`BytesMut`和`BufMut`时,容量是**未初始化**的. `BytesMut`抽象阻止了我们读取取未初始化的内存. 这使得我们避免了 209 | 初始化的步骤. 210 | 211 | ## 解析(Parsing) 212 | 现在,让我们来看看`parse_frame()`函数. 解析的过程分两步: 213 | 214 | 1. 确保已经缓冲整个帧并找到帧结束索引. 215 | 2. 解析一个帧. 216 | 217 | `mini-redis` 包提供给我们一个解决上面两步功能的函数: 218 | 219 | 1. [Frame::check](https://docs.rs/mini-redis/0.3/mini_redis/frame/enum.Frame.html#method.check) 220 | 2. [Frame::parse](https://docs.rs/mini-redis/0.3/mini_redis/frame/enum.Frame.html#method.parse) 221 | 222 | 我们也将重用`Buf`抽象来得到帮助. 一个`Buf` 传递到`Frame::check`中去. 当`check`函数迭代传入buffer时, 内部的游标也会前进. 当`check` 223 | 函数返回时, 缓冲区(buffer)的内部游标会指向帧的末尾. 224 | 225 | 对于`Buf`的类型,我们使用 [std::io::Cursor<&[u8]>](https://doc.rust-lang.org/stable/std/io/struct.Cursor.html) 226 | 227 | ```rust 228 | use mini_redis::{Frame, Result}; 229 | use mini_redis::frame::Error::Incomplete; 230 | use bytes::Buf; 231 | use std::io::Cursor; 232 | 233 | fn parse_frame(&mut self) 234 | -> Result> 235 | { 236 | // 创建一个 T:Buf 类型 237 | let mut buf = Cursor::new(&self.buffer[..]); 238 | 239 | // 检查是否为一个完整可用的帧 240 | match Frame::check(&mut buf) { 241 | Ok(_) => { 242 | // 得到帧的字节长度 243 | let len = buf.position() as usize; 244 | 245 | // 调用parse来重围内部游标 246 | buf.set_position(0); 247 | 248 | // 解析帧 249 | let frame = Frame::parse(&mut buf)?; 250 | 251 | // 从缓冲区中丢弃帧 252 | self.buffer.advance(len); 253 | 254 | // 返回帧的调用者 255 | Ok(Some(frame)) 256 | } 257 | // 没有足够数据被缓存的情况 258 | Err(Incomplete) => Ok(None), 259 | // 一个错误被捕获 260 | Err(e) => Err(e.into()), 261 | } 262 | } 263 | ``` 264 | 265 | 完整的 [Frame::check](https://github.com/tokio-rs/mini-redis/blob/tutorial/src/frame.rs#L63-L100) 函数代码可在这里找到. 我们不会完全的介绍它. 266 | 需要注意的是`Buf`使用了"字节迭代器"风格的API. 它们获取数据并推进游标. 比如, 为了解析一个帧,检查第一个字节来确定帧的类型. 这样的功能使用 267 | [Buf::get_u8](https://docs.rs/bytes/0.6/bytes/buf/trait.Buf.html#method.get_u8) . 它会获取游标位置的字节,并将游标前进一位. 268 | 269 | 在[Buf](https://docs.rs/bytes/0.6/bytes/buf/trait.Buf.html) trait上还有更多有用的方法. 查看[API docs](https://docs.rs/bytes/0.6/bytes/buf/trait.Buf.html) 来了解更多细节. 270 | 271 | ## 缓冲写(Buffered writes) 272 | 帧相关的API另外一半是`write_frame(frame)`函数. 此函数将整个帧写入到socket中. 为了最小化`write`的系统调用, 写入将先被缓冲. 在写入到socket之前, 273 | 将维持一个写缓冲区并将帧编码到此缓冲区. 274 | 275 | 考虑到大数据量(bulk)的帧流. 要使用`Frame::Bulk(Bytes)`来写入. bulk帧有一个帧头, 它由`$`符后跟数据长度(以字节为单位)组成. 帧的大部分都是`Bytes`值的内容. 276 | 如果数据很大,则将其复制到中间缓冲区将会是非常昂贵的操作. 277 | 278 | 为了实现写缓冲, 我们将使用 [BufWriter struct](https://docs.rs/tokio/0.3/tokio/io/struct.BufWriter.html) . 这个结构体使用`T:AsyncWrite`初始化, 279 | 并自身实现了`AsyncWrite`. 当在`BufWriter`上调用`write`时,写操作不会直接传递给内部写程序,而是传递给缓冲区. 当缓冲区满时, 内容会刷新到内部写入器,并清除内部缓冲区. 280 | 在某些情况下,还有一些优化可以绕过缓冲区直接写到内部写入器. 281 | 282 | 在本指引的这部分,我们将不会去尝试实现一个完整的`write_frame()`功能. 完整的实现请查看[这里](https://github.com/tokio-rs/mini-redis/blob/tutorial/src/connection.rs#L159-L184). 283 | 284 | 首先更新`connection`结构体: 285 | 286 | ```rust 287 | use tokio::io::BufWriter; 288 | use tokio::net::TcpStream; 289 | use bytes::BytesMut; 290 | 291 | pub struct connection { 292 | stream: BufWriter, 293 | buffer: BytesMut, 294 | } 295 | 296 | impl connection { 297 | pub fn new(stream: TcpStream) -> connection { 298 | connection { 299 | stream: BufWriter::new(stream), 300 | buffer: BytesMut::with_capacity(4096), 301 | } 302 | } 303 | } 304 | ``` 305 | 306 | 然后, 实现`write_frame()`. 307 | 308 | ```rust 309 | use tokio::io::{self, AsyncWriteExt}; 310 | use mini_redis::Frame; 311 | 312 | async fn write_frame(&mut self, frame: &Frame) 313 | -> io::Result<()> 314 | { 315 | match frame { 316 | Frame::Simple(val) => { 317 | self.stream.write_u8(b'+').await?; 318 | self.stream.write_all(val.as_bytes()).await?; 319 | self.stream.write_all(b"\r\n").await?; 320 | } 321 | Frame::Error(val) => { 322 | self.stream.write_u8(b'-').await?; 323 | self.stream.write_all(val.as_bytes()).await?; 324 | self.stream.write_all(b"\r\n").await?; 325 | } 326 | Frame::Integer(val) => { 327 | self.stream.write_u8(b':').await?; 328 | self.write_decimal(*val).await?; 329 | } 330 | Frame::Null => { 331 | self.stream.write_all(b"$-1\r\n").await?; 332 | } 333 | Frame::Bulk(val) => { 334 | let len = val.len(); 335 | 336 | self.stream.write_u8(b'$').await?; 337 | self.write_decimal(len as u64).await?; 338 | self.stream.write_all(val).await?; 339 | self.stream.write_all(b"\r\n").await?; 340 | } 341 | Frame::Array(_val) => unimplemented!(), 342 | } 343 | 344 | self.stream.flush().await; 345 | 346 | Ok(()) 347 | } 348 | ``` 349 | 350 | 此处使用的功能由`AsyncWriteExt`提供. 它们也可以在`TcpStream`上使用,但不建议在没有中间缓冲区的情况下发出单字节写操作. 351 | 352 | * [write_u8](https://docs.rs/tokio/0.3/tokio/io/trait.AsyncWriteExt.html#method.write_u8) 写入单个字节到writer上. 353 | * [write_all](https://tokio.rs/tokio/tutorial/framing) 将整个切片写到writer上. 354 | * [write_decimal](https://github.com/tokio-rs/mini-redis/blob/tutorial/src/connection.rs#L225-L238) 由mini-redis来实现. 355 | 356 | 函数的末尾调用`self.stream.flush().await`. 是因为`BufWriter` 将写操作存储到中间缓冲区上, 因此写调用不能保证将数据写到socket中. 357 | 在返回前,我们希望装饰帧写入到socket中. 调用`flush()`将缓冲区中的所有数据写入到socket中. 358 | 359 | 另外一种二选一的方法是,不在`write_frame()`中调用`flush()`. 而是在`connection`上提供`flush()`函数. 这将允许调用者将队列中的多个小帧 360 | 写入到队列, 然后使用系统调用写入将它们全写入到socket中. 但这样做会使用`Coonection`API变得复杂. 简洁是Mini-Redis的目标之一, 因此我们决定在 361 | `fn write_frame()` 中包含`flush().await`的调用. 362 | 363 | 364 | 365 | ← [I/O](IO.md) 366 | 367 | → [深入异步](AsyncInDepth.md) -------------------------------------------------------------------------------- /doc/Glossary.md: -------------------------------------------------------------------------------- 1 | ## 词汇表(Glossary) 2 | ### 异步(Asynchronous) 3 | 在Rust的上下文中,异步代码指的是使用了`async/await`语言特性的代码,该功能允许很多任务在几个线程(甚至单个线程)上同时运行. 4 | 5 | ### 并发与并行(Concurrency and parallelism) 6 | 并发与并行是两个相关的概念,在谈论到同时执行多个任务时都会使用. 如果某件事并行发生,那么它也是同时发生,但事实上并非如此:在两个任务之间 7 | 交替操作,但从来没同时执行这两个任务,这种情况是并发而不是并行. 8 | 9 | ### Future 10 | Future 是存储某些操作当前状态的值. Future也有轮询方法,该方法使操作可以继续进行,直到需要等待的某些内容(比如网络连接)为止. 调用`poll`方法 11 | 应该很快返回. 12 | 13 | Future通常可以在异步块中使用`.await`组合多个future来创建. 14 | 15 | ### 执行器与调度器(Executor/scheduler) 16 | 执行器与调度器通过重复调用`poll`方法来执行Future. 标准库中并没有执行器,所以你需要额外的库,并且Tokio的**运行时**提供了使用最广泛的执行器. 17 | 18 | 执行器可以在几个线程上同时运行大量的Future. 它通过在等待时交换当前正在执行的任务来执行此操作. 如果代码很长时间也没有达到`.await`,则称为 19 | "阻塞了线程"或者"没有回到执行器",这将阻塞其它任务的运行. 20 | 21 | ### 运行时(Runtime) 22 | **运行时**是一种包含执行程序和与执行程序集成的各种实用程序库,比如计时器程序与IO. 运行时与执行器的名称有时候可以交换来使用. 标准库中没有运行时, 23 | 因此你要使用它就得添加额外的库,并且使用最广泛的运行时是Tokio运行时. 24 | 25 | 运行时也被用在其它上下文中,比如说,"Rust没有运行时" 的短语有时候表示Rust程序的执行没有垃圾回收或者即时编译. 26 | 27 | ### 任务(Task) 28 | 一个任务它是一个运行在Tokio运行时上的操作,它被`tokio::spawn`或者`Runtime::block_on`函数创建. 通过组合它们来创建Future的工具,比如, 29 | `.await`和`join!`不创建新的任务,每个合并的部分都被称为"在同一个任务中". 30 | 31 | 并行性需要多个任务,但是可以使用比如`join!`之类的工具同时对一项任务执行多个操作. 32 | 33 | ### 产生(Spawning) 34 | Spawning被表示在使用`tokio::spawn`函数来创建一个新任务. 它在标准库 [std::thread::spawn](https://doc.rust-lang.org/stable/std/thread/fn.spawn.html) 中也指创建新线程. 35 | 36 | ### 异步块(Async block) 37 | 异步块是一种用来创建Future运行某些代码的简便方法. 比如: 38 | 39 | ```rust 40 | let world = async { 41 | println!("world"); 42 | } 43 | 44 | let my_future = async { 45 | println!("Hello"); 46 | world.await; 47 | } 48 | ``` 49 | 50 | 上面的代码创建了一个叫作`my_future`的Future,它会打印出`Hello world!`. 它会首先打印出Hello,然后再运行`world` future. 注意上面的代码 51 | 不会自己打印出任何的内容 - 你必须在发生一些事之前实际的执行`my_future`,方法是直接spawning它,或者在有spawning的地方使用`.await`. 52 | 53 | ### 异步函数(Async function) 54 | 与异步块类似,一个异步函数是创建函数体成为future的一种便捷方法. 所有的异步函数都可以被重写为返回future的普通函数: 55 | 56 | ```rust 57 | async fn do_stuff(i: i32) -> String { 58 | // do stuff 59 | format!("The integer is {}.", i) 60 | } 61 | ``` 62 | 63 | ```rust 64 | use std::future::Future; 65 | 66 | // 上面的异步函数可以用以下同种方式表述: 67 | fn do_stuff(i: i32) -> impl Future { 68 | async move { 69 | // do stuff 70 | format!("The integer is {}.", i) 71 | } 72 | } 73 | ``` 74 | 75 | 这里使用了[impl Trait syntax](https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits) 语法来返回一个future, 76 | 因为[Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html)是一个trait. 请注意,因为异步块创建的future在执行之前不会 77 | 执行任何操作,因此调用异步函数在返回的future被执行前也不会执行任何操作([ignoring it triggers a warning](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4faf44e08b4a3bb1269a7985460f1923)). 78 | 79 | ### Yielding 80 | 在Rust异步上下文中,yield指允许执行器在单个线程上执行很多的future. future的每一次出让(yield),执行器都会使用另外一个future交换当前future, 81 | 通过这种重复的交换当前任务,执行器就可以同时的(并发的)执行大量的任务. future仅能使用`.await`操作符来yield,因此两次`.await`操作之间花费很长时间 82 | 的future就可能阻塞其它任务的执行. 83 | 84 | 具体来说,从[poll](https://doc.rust-lang.org/stable/std/future/trait.Future.html#method.poll) 方法返回时,future就会yields. 85 | 86 | ### 阻塞(Blocking) 87 | 单词 "blocking" (阻塞) 有两种不同的使用方式: "阻塞"的第一层意思是等待某些事完成,"阻塞"的另外一层含义是指当一个future花费很长时间而没有yielding时. 88 | 为了明确起见,可以将短语"blocking the thread"(阻塞线程)用于第二种含义. 89 | 90 | 在Tokio的文档中总是使用第二种"阻塞"的含义. 91 | 92 | 要在Tokio中运行阻塞的代码,请参考Tokio API指引中的[CPU-bound tasks and blocking code](https://docs.rs/tokio/0.3/tokio/#cpu-bound-tasks-and-blocking-code) 章节. 93 | 94 | ### 流(Stream) 95 | [Stream](https://docs.rs/tokio/0.3/tokio/stream/trait.Stream.html) 是 [Iterator](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html) 的异步版本, 96 | 并提供值流. 通常与`while let` 循环一起使用,如下所示: 97 | 98 | ```rust 99 | use tokio::stream::StreamExt; // for next() 100 | 101 | while let Some(item) = stream.next().await { 102 | // do something 103 | } 104 | ``` 105 | 106 | 单词`stream`有时候用来指 [AsyncRead](https://docs.rs/tokio/0.3/tokio/io/trait.AsyncRead.html) 和 [AsyncWrite](https://docs.rs/tokio/0.3/tokio/io/trait.AsyncWrite.html) 有点令人困惑. 107 | 108 | ### 通道(Channel) 109 | 通道是一种允许一部分代码发送消息到另外一部分的工具. Tokio提供了一些通道,每一种都有其目的与用途. 110 | 111 | * [mpsc](https://docs.rs/tokio/0.3/tokio/sync/mpsc/index.html) : 多生产者,单消费者通道. 可以发送许多的值. 112 | * [oneshot](https://docs.rs/tokio/0.3/tokio/sync/oneshot/index.html) : 单生产者,单消费者通道. 能发送单一值. 113 | * [broadcast](https://docs.rs/tokio/0.3/tokio/sync/broadcast/index.html) : 多生产者,多消费者通道. 发送很多值,每一个接收者都能看到每一个值. 114 | * [watch](https://docs.rs/tokio/0.3/tokio/sync/watch/index.html) : 单生产者,多消费者通道,可以发送许多值,但不会保留历史记录. 接收者仅能看到最近的值. 115 | 116 | 如果你需要使用多生产者,多消费者通道,且仅能有一个消费者能看到每一个消息,你可以使用 [async-channel](https://docs.rs/async-channel/) 包. 117 | 118 | 还有一些在异步Rust之外使用的通道,比方说 [std::sync::mpsc](https://doc.rust-lang.org/stable/std/sync/mpsc/index.html) 和 [crossbeam::channel](https://docs.rs/crossbeam/latest/crossbeam/channel/index.html) . 119 | 这些channels 通过阻塞线程来等待消息,在这异步代码中是不被允许的. 120 | 121 | ### 背压(Backpressure) 122 | 背压是一种用来设计高负载低延迟响应,应用的一种模式. 比如说,`mpsc` 以有界和无界的形式出现. 通过使用有界通道,如果接收方无法及时处理发送方发送的消息数量时, 123 | 接收方可以对发送方施加 "背压",这可以避免内存的使用量一直增长不受限制,因为通道上发送的消息越来越多了. 124 | 125 | ### Actor 126 | 一种设计应用程序的设计模式. Actor是指独立产生的任务,该任务代表应用程序的其它部分使用channel与应用程序的另外部分通信来管理某些资源. 127 | 128 | 有关 actor的示例,请参考 [通道](Channels.md) 章节. 129 | 130 | ← [指南](../README.md) -------------------------------------------------------------------------------- /doc/GracefulShutdown.md: -------------------------------------------------------------------------------- 1 | ## 优雅关机(Graceful Shutdown) 2 | 这篇文章的目的是告诉你如何在异步应用中正常的关机。 3 | 4 | 要实现优雅关机一般有3个部分: 5 | 6 | * 确定何时关机 7 | * 告诉程序每一部分关闭 8 | * 等待程序的其它部分关闭 9 | 10 | 文章的剩余部分将介绍这三部分。可以在 [mini-redis](https://github.com/tokio-rs/mini-redis/) 中找到真实世界 11 | 如何正确关机的实现,特别是在 [src/server.rs](https://github.com/tokio-rs/mini-redis/blob/master/src/server.rs) 和 12 | [src/shutdown.rs](https://github.com/tokio-rs/mini-redis/blob/master/src/shutdown.rs) 文件中有. 13 | 14 | ### 确定何时关机(Figuring out when to shut down) 15 | 这一点肯定是取决于应用程序,但有一个很关键的标准是应用程序从操作系统接收一个信号。这种情况发生在,当你的应用程序运行在终端时按 `ctrl+c` 16 | 时。为了侦探到这个信号,`Tokio` 提供了一个 [tokio::signal::ctrl_c](https://docs.rs/tokio/1/tokio/signal/fn.ctrl_c.html) 函数, 17 | 你可以像下面这样来使用它: 18 | 19 | ```rust 20 | use tokio::signal; 21 | 22 | #[tokio::main] 23 | async fn main() { 24 | // ... 产生一个其它任务 task ... 25 | 26 | match signal::ctrl_c().await { 27 | Ok(()) => {}, 28 | Err(err) => { 29 | eprintln!("Unable to listen for shutdown signal: {}", err); 30 | // 关闭的时候也可能出现错误 31 | }, 32 | } 33 | 34 | // 发送一个关机信号给应用程序并等待 35 | } 36 | ``` 37 | 38 | 如果你有多个关机条件,你可以使用 [mpsc channel](https://docs.rs/tokio/1/tokio/sync/mpsc/index.html) 来将关机信息发送到一个地方。 39 | 然后你可以在channel上通过 [Select](https://docs.rs/tokio/1/tokio/macro.select.html) 匹配到 `ctrl_c` 信号。比如像下面这样: 40 | 41 | ```rust 42 | use tokio::signal; 43 | use tokio::sync::mpsc; 44 | 45 | #[tokio::main] 46 | async fn main() { 47 | let (shutdown_send, shutdown_recv) = mpsc::unbounded_channel(); 48 | 49 | // ... 产生一个其它任务 task ... 50 | // 51 | // application uses shutdown_send in case a shutdown was issued from inside 52 | // 应用使用 shutdown_send 发出关机信息来防止应用从内部关闭 53 | // the application 54 | 55 | tokio::select! { 56 | _ = signal::ctrl_c() => {}, 57 | _ = shutdown_recv.recv() => {}, 58 | } 59 | 60 | // 发送一个关机信号给应用程序并等待 61 | } 62 | ``` 63 | 64 | ### 告之关机的一些事情(Telling things to shut down) 65 | 告诉应用程序每一部分关闭时常用的工具是 [broadcast channel](https://docs.rs/tokio/1/tokio/sync/broadcast/index.html) 。 66 | 想法其实很简单,应用程序中的每一个任务都有一个广播(broadcast) 通道(channel)接收器,当消息在channel上广播时,任务会自行关闭。通常, 67 | 使用 [tokio::select](https://docs.rs/tokio/1/tokio/macro.select.html) 来接收这个广播消息。比如在 `mini-redis` 的每一个 68 | 任务中来接收 `shutdown` 消息的方式: 69 | 70 | ```rust 71 | let next_frame = tokio::select! { 72 | res = self.connection.read_frame() => res?, 73 | _ = self.shutdown.recv() => { 74 | // If a shutdown signal is received, return from `run`. 75 | // 如果一个 shutdown 信号被接收到,将从 `运行` 状态返回,并将导致此任务终止. 76 | // This will result in the task terminating. 77 | return Ok(()); 78 | } 79 | }; 80 | ``` 81 | 82 | 在 `mini-redis` 的示例中,当一个关机信号被接收到时,task(任务)会立即终止,但有时候你需要在终止任务之前运行一个`关机过程`。比方说, 83 | 有时候你需要在关机前将数据刷到一个文件或数据库中,或者有任务管理的链接,你可能想在任务终止前在链接上发送关机消息。 84 | 85 | 有一个很好的方式是,将 `broadcast channel` 包装到一个 struct 中。这里有一个示例 [这里](https://github.com/tokio-rs/mini-redis/blob/master/src/shutdown.rs) 。 86 | 87 | 值得一提的是你也可以使用 [watch channel](https://docs.rs/tokio/1/tokio/sync/watch/index.html) 来达到同样的效果。这两种方式之间没有明显的差异。 88 | 89 | ### 等待一些事情完成关闭(Waiting for things to finish shutting down) 90 | 91 | 一旦你告诉另一个任务要关闭时,你需要等待它们完成。最简单的方法是使用 [mpsc channel](https://docs.rs/tokio/1/tokio/sync/mpsc/index.html) 92 | 这里不是发送消息,而是等待通道的关闭,这时每一个sender都会被丢弃。 93 | 94 | 下面是上面这种方式的简单示例,示例生成10个任务,然后使用 `mpsc` 通道等待它们关闭。 95 | 96 | ```rust 97 | use tokio::sync::mpsc::{channel, Sender}; 98 | use tokio::time::{sleep, Duration}; 99 | 100 | #[tokio::main] 101 | async fn main() { 102 | let (send, mut recv) = channel(1); 103 | 104 | for i in 0..10 { 105 | tokio::spawn(some_operation(i, send.clone())); 106 | } 107 | 108 | // 等待此任务task完成 109 | // 110 | // We drop our sender first because the recv() call otherwise 111 | // 我们丢弃drop掉 sender 是因为 recv()的调用,不然的话将会一直休眠 112 | // sleeps forever. 113 | drop(send); 114 | 115 | // When every sender has gone out of scope, the recv call 116 | // 当每个 sender 超过作用域时,recv 的调用将返回error。这里我们忽略它。 117 | // will return with an error. We ignore the error. 118 | let _ = recv.recv().await; 119 | } 120 | 121 | async fn some_operation(i: u64, _sender: Sender<()>) { 122 | sleep(Duration::from_millis(100 * i)).await; 123 | println!("Task {} shutting down.", i); 124 | 125 | // sender 离开了作用域 ... 126 | } 127 | ``` 128 | 129 | 有个很重要的点是,等待关闭的任务都持有一个sender. 在这种情况下你必须确保等待通道关闭之前删除此sender。 130 | 131 | ← [同步代码桥接](BridgingWithSyncCode.md) 132 | 133 | → [词汇表](Glossary.md) -------------------------------------------------------------------------------- /doc/HelloTokio.md: -------------------------------------------------------------------------------- 1 | ## 你好 Tokio(Hello Tokio) 2 | 我们将通过编写一个非常基础的Tokio应用来开始. 它可以连接到Mini-Redis服务, 并设置键 `hello` 的值为 `world` . 然后它可以读取这个键, 这将 3 | 使用Mini-Redis客户端完成. 4 | 5 | ## 实现代码(The code) 6 | ### 生成一个新的包 7 | 让我们创建一个新的Rust app: 8 | ```shell script 9 | cargo new my-redis 10 | cd my-redis 11 | ``` 12 | 13 | ### 添加依赖(Add dependencies) 14 | 下一步, 打开 `Cargo.toml` 并在 `[dependencies]` 下添加如下依赖: 15 | ```shell script 16 | tokio = {version = "0.2", features = ["full"]} 17 | mini-redis = "0.2" 18 | ``` 19 | 20 | ### 编写代码(Write the code) 21 | 然后, 打开 `main.rs` 并使用如下内容替换: 22 | ```rust 23 | use mini_redis::{client, Result}; 24 | 25 | #[tokio::main] 26 | pub async fn main() -> Result<()> { 27 | // 打开链接到mini-redis的链接 28 | let mut client = client::connect("127.0.0.1:6379").await?; 29 | 30 | // 设置 "hello" 键的值为 "world" 31 | client.set("hello", "world".into()).await?; 32 | 33 | // 获取"hello"的值 34 | let result = client.get("hello").await?; 35 | 36 | println!("got value from the server; result={:?}", result); 37 | 38 | Ok(()) 39 | } 40 | ``` 41 | 确保 Mini-Redis服务正在运行. 在另外一个终端窗口中运行: 42 | ```shell script 43 | mini-redis-server 44 | ``` 45 | 现在, 运行 `my-redis` 应用: 46 | ```shell script 47 | cargo run 48 | got value from the server; result=Some(b"world") 49 | ``` 50 | 成功了! 51 | 52 | 你可以在 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/hello-tokio/src/main.rs) 找到完整的代码. 53 | 54 | ## 过程分解(Breaking it down) 55 | 让我们花一点时间来回顾一下刚刚上面做的事情. 这里没有太多的代码, 但是却发生了很多事. 56 | ```rust 57 | let mut client = client::connect("127.0.0.1:6379").await?; 58 | ``` 59 | `client::connect` 函数功能由 `mini-redis` 包提供. 它通过一个指定的远程地址异步的建立一个TCP链接. 一旦链接被建立, 一个 `client` 处理器就会被返回. 60 | 即使操作是异步的,但我们写的代码看起来是同步的. 操作是异步的唯一标识是 `.await` 操作符. 61 | 62 | ### 什么是异步编程?(what is asynchronous programming?) 63 | 大多数计算机程序的执行顺序都是按程序编写的顺序来执行的. 第一行代码先执行,然后是下一行,这样一直下去. 对于同步编程, 当程序遇到不能立即完成的操作时, 64 | 它将被阻塞直到该操作完成为止. 比方说, 建立TCP链接需要对等方通过网络进行交换, 这一过程可能需要相当长的时间, 期间线程是阻塞的. 65 | 66 | 对于异步编程不能立即完成的操作会被挂起到后台. 当前线程不会被阻塞, 并且能继续运行其它的事. 一旦操作完成, 任务将从中断处继续处理. 我们前面的示例 67 | 只有一个任务, 因此在挂起时什么也没发生, 但是通常异步程序有很多这样的任务. 68 | 69 | 尽管异步编程可以使得应用程序更快, 但它通常也会导致程序复杂的多. 一旦异步操作完成, 就需要程序员跟踪恢复工作所需的所有状态. 从历史角度来看, 这是一个非常 70 | 乏味且容错出错的任务. 71 | 72 | ### 编译时绿色线程(Compile-time green-threading) 73 | Rust使用被叫作 `async/await` 的feature实现异步编程. 执行异步操作的函数用 `async` 关键字来标记. 在我们的示例当中, `connect` 函数被定义像下面这样: 74 | ```rust 75 | use mini_redis::Result; 76 | use mini_redis::client::Client; 77 | use tokio::net::ToSocketAddress; 78 | 79 | pub async fn connect(addr: T) -> Result { 80 | // ... 81 | } 82 | ``` 83 | 使用 `async fn` 的定义看起来像同步函数一样, 但是操作是异步的. Rust在编译时将转换 `async fn` 为异步操作. 任何在 `async fn` 中的 `.await` 84 | 调用都会将控制权返回给线程. 在后台进行操作时, 线程可能会做其它的工作. 85 | 86 | ```text 87 | 尽管其它语言也实现了 `async/await`, 但是Rust的实现比较独特. 主要是Rust的异步操作是惰性(lazy)的. 结果就是导致与其它语言不同的运行时语义. 88 | ``` 89 | 90 | 如果这样说还不太明白其意义,请不用担心. 我们将在本指南中进一步探讨 `async/await` . 91 | 92 | ### 使用 `async/await`(Using `async/await` ) 93 | 异步函数的调用与其它Rust函数一样. 但是调用这些函数不会导致函数体执行(译者注: 即是一种声明不会立即执行). 而是调用这些函数返回表示操作的值. 94 | 从概念上讲,这类似于零参数闭包. 为了实际的去运行这些操作, 你应该使用 `.await` 操作符来返回值. 95 | 96 | 通过下面的程序举例: 97 | ```rust 98 | async fn say_world() { 99 | println!("world"); 100 | } 101 | 102 | #[tokio::main] 103 | async fn main() { 104 | // 调用 say_world函数没有立即执行 say_world() 函数体 105 | let op = say_world(); 106 | 107 | // 这里会首先打印 108 | println!("hello"); 109 | 110 | // 调用 .await 操作才会执行say_world 111 | op.await; 112 | } 113 | ``` 114 | 输出: 115 | ```text 116 | hello 117 | world 118 | ``` 119 | `async fn` 返回值是一个实现了 `Future` trait的异步类型. 120 | 121 | ### 异步 `main` 函数(Async `main` function) 122 | main 函数用来启动应用, 它与大多数Rust其它包中的函数不同: 123 | 124 | * 1. 它是一个 `async fn` . 125 | * 2. 它使用 `#[tokio::main]` 注解. 126 | 127 | 我们要进入一个异步上下文时,一个 `async fn` 被使用. 但是异步函数必须由一个运行时 [runtime](https://docs.rs/tokio/0.2/tokio/runtime/index.html) 来执行. 128 | 运行时包含异步任务调度器(scheduler), 提供I/O事件, 计时器(timers)等等. 运行时不会自动开始,因此需要main函数来启动它. 129 | 130 | `#[tokio::main]` 函数宏. 它将 `async fn main()` 转换为一个初始化一个运行时实例且执行异步main函数的 同步 `fn main()`. 131 | 132 | 比如说下面的示例: 133 | ```rust 134 | #[tokio::main] 135 | async fn main() { 136 | println!("hello"); 137 | } 138 | ``` 139 | 转换后的结果: 140 | ```rust 141 | fn main() { 142 | let mut rt = tokio::runtime::Runtime::new().unwrap(); 143 | rt.block_on(async { 144 | println!("hello"); 145 | }) 146 | } 147 | ``` 148 | tokio运行时的细节将在后面介绍. 149 | 150 | ### Cargo 特性(Cargo features) 151 | 当本教程中的Tokio依赖,启用了 `full` 特性时: 152 | ```toml 153 | tokio = {version = "0.2", features = ["full"]} 154 | ``` 155 | Tokio有很多功能(TCP,UDP,Unix 套接字, 定时器(timers), 同步工具(sync utilities),多种调度器类型(multiple scheduler types), 等等). 156 | 不是所有的应用都需要所有的功能. 当我们尝试去优化编译时间或者应用占用空间时, 应用程序可以去选择仅仅它需要使用的特性. 157 | 158 | 比如现在我们在tokio的依赖中使用了 "full" 的特性. 159 | 160 | ← [指南](Introduction.md) 161 | 162 | → [Spawning](Spawning.md) 163 | -------------------------------------------------------------------------------- /doc/IO.md: -------------------------------------------------------------------------------- 1 | ## I/O 2 | 3 | 在Tokio中的I/O操作几乎与`std`的相同, 但是(Tokio中的I/O操作是)是异步的. 这里有关于读( [AsyncRead](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncRead.html) )和写( [AsyncWrite](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncWrite.html) )的trait. 特定的类型适当的实现了这些trait, 比如:( [TcpStream](https://docs.rs/tokio/0.2/tokio/net/struct.TcpStream.html), [File](https://docs.rs/tokio/0.2/tokio/fs/struct.File.html), [Stdout](https://docs.rs/tokio/0.2/tokio/io/struct.Stdout.html) ) `AsyncRead` 与 `AsyncWrite` 也可以通过许多数据结构来实现, 例如, `Vec` 和 `&[u8]` . 这允许在需要一个reader与writer的地方使用字节数组. 4 | 5 | 在本章节页中, 会介绍使用Tokio来进行基本的I/O读写操作过程, 并通过一些示例进行介绍. 在下一页中我们将获得更多的关于I/O操作的高级示例. 6 | 7 | ## `异步读` 和 `异步写` (`AsyncRead` and `AsyncWrite`) 8 | 这两个trait为异步读和写入字节流提供了便利性. 这两个trait中的方法通常不能直接的调用, 就好像你不能从`Future` trait中手动的调用 `poll` 方法一样. 9 | 取而代之是, 你将通过 `AsyncReadExt` 与 `AsyncWriteExt` 提供的实用程序方法来使用它. 10 | 11 | 让我们简单的看看其中的几个方法. 所有的方法都是异步的且必须使用 `.await`. 12 | 13 | ### `async fn read()` 14 | 15 | [AsyncReadExt::read](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncReadExt.html#method.read) 提供了一个异步的用来读取数据到缓冲区中的方法,并返回读取的字节数. 16 | 17 | **注意** : 当 `read()` 返回 `Ok(0)` 时, 这表明流已被关闭了. 对 `read()` 的任何其它的调用将立即返回`Ok(0)`完成. 对于 [TcpStream](https://docs.rs/tokio/0.2/tokio/net/struct.TcpStream.html) 实例, 这表明socket的读取部分已经关闭. 18 | 19 | ```rust 20 | use tokio::fs::File; 21 | use tokio::io::{self, AsyncReadExt}; 22 | 23 | #[tokio::main] 24 | async fn main() -> io::Result<()> { 25 | let mut f = File::open("foo.txt").await?; 26 | let mut buffer = [0; 10]; 27 | 28 | // 读取10个字节 29 | let n = f.read(&mut buffer[..]).await?; 30 | 31 | println!("The bytes: {:?}", &buffer[..n]); 32 | Ok(()) 33 | } 34 | ``` 35 | 36 | ### `async fn read_to_end()` 37 | 38 | [AsyncReadExt::read_to_end](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncReadExt.html#method.read_to_end) 39 | 从流中读取所有的字节直到遇到 EOF. 40 | 41 | ```rust 42 | use tokio::io::{self, AsyncReadExt}; 43 | use tokio::fs::File; 44 | 45 | #[tokio::main] 46 | async fn main() -> io::Result<()> { 47 | let mut f = File::open("foo.txt").await?; 48 | let mut buffer = Vec::new(); 49 | 50 | // 读取整个文件 51 | f.read_to_end(&mut buffer).await?; 52 | Ok(()) 53 | } 54 | ``` 55 | 56 | ### `async fn write()` 57 | 58 | [AsyncWriteExt::write](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncWriteExt.html#method.write) 将缓冲区中的数据写入到writer 59 | 并返回写入的字节数. 60 | 61 | ```rust 62 | use tokio::io::{self, AsyncWriteExt}; 63 | use tokio::fs::File; 64 | 65 | #[tokio::main] 66 | async fn main() -> io::Result<()> { 67 | let mut file = File::create("foo.txt").await?; 68 | 69 | // 写入字字节符串的一些前缀, 但不一定是全部 70 | let n = file.write(b"some bytes").await?; 71 | 72 | println!("Write the first {} bytes of 'some bytes'.", n); 73 | Ok(()) 74 | } 75 | ``` 76 | 77 | ### `async fn write_all()` 78 | 79 | [AsyncWriteExt::write_all](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncWriteExt.html#method.write_all) 将整个缓存区写入到writer. 80 | 81 | ```rust 82 | use tokio::io::{self, AsyncWriteExt}; 83 | use tokio::fs::File; 84 | 85 | #[tokio::main] 86 | async fn main() -> io::Result<()>{ 87 | let mut buffer = File::create("foo.txt").await?; 88 | 89 | buffer.write_all(b"some bytes").await?; 90 | Ok(()) 91 | } 92 | ``` 93 | 这两个trait都包含了其它有用的方法. 有关完整的列表, 请参考API文档. 94 | 95 | ## 辅助函数(Helper functions) 96 | 另外, 与 `std` 包中一样, `tokio::io`模块也包含了一些有用的实用函数和用于处理标准输入,输出,错误的API. [standard input](https://docs.rs/tokio/0.2/tokio/io/fn.stdin.html), 97 | [standard output](https://docs.rs/tokio/0.2/tokio/io/fn.stdout.html), [standard error](https://docs.rs/tokio/0.2/tokio/io/fn.stderr.html) . 98 | 比如, `tokio::io::copy` 可以异步将reader中的全部内容复制到writer中去. 99 | 100 | ```rust 101 | use tokio::fs::File; 102 | use tokio::io; 103 | 104 | #[tokio::main] 105 | async fn main() -> io::Result<()> { 106 | let mut reader: &[u8] = b"hello"; 107 | let mut file = File::create("foo.txt").await?; 108 | 109 | io::copy(&mut reader, &mut file).await?; 110 | Ok(()) 111 | } 112 | ``` 113 | 114 | 注意, 这利用了字节数组也实现了 `AsyncRead` 这一特点. 115 | 116 | ## 回声服务器(Echo server) 117 | 让我们练习一些异步I/O. 我们将编写一个回声服务. 118 | 119 | 此回声服务绑定一个 `TcpListener` 且在一个循环中接收入站链接. 对于每个链接将从socket中读取数据并将数据立即写回到socket中. 120 | 客户端发送数据到服务端并接收回同样的返回. 121 | 122 | 我们将使用略微不同的策略来两次实现echo服务. 123 | 124 | ### 使用 `io::copy()` (Using `io::copy()`) 125 | 首先,我们将使用`io::copy()` 实现echo的逻辑部分. 126 | 127 | 这是一个TCP服务,需要一个accept循环. 产生一个任务来处理每一个被接收的Socket链接. 128 | 129 | ```rust 130 | use tokio::io; 131 | use tokio::net::TcpListener; 132 | 133 | #[tokio::main] 134 | async fn main() -> io::Result<()> { 135 | let mut listener = TcpListener::bind("127.0.0.1:6124").await.unwrap(); 136 | loop { 137 | let (mut socket, _) = listener.accept().await?; 138 | tokio::spawn(async move { 139 | // 这里Copy数据 140 | }); 141 | } 142 | } 143 | ``` 144 | 145 | 和上面看到的一样, 这个实用函数需要一个reader和一个writer并从它们中的一个复制数据到另外一个中去. 然而, 我们只有一个`TcpStream`. 146 | 该单一值同时实现了`AsyncReader`和`AsyncWrite`. 因为`io::copy`的reader和writer都需要`&mut`, 所有socket不能同时用于两个参数. 147 | 148 | ```rust 149 | // 这样无法编译 150 | io::copy(&mut socket, &mut socket).await?; 151 | ``` 152 | 153 | ### 拆分reader与writer(Splitting a reader + writer) 154 | 为了解决这个问题, 我们必须分割socket到一个reader处理器与一个writer处理器中去. 拆分一个reader/writer组合最佳的方法依赖一个特定的类型. 155 | 任何reader+writer类型都能被 `io::split` 工具拆分. 这个函数传入单个值,并返回单独的reader和writer处理器. 这两个处理器可以单独的使用, 156 | 包括从不同的任务中. 157 | 158 | 比如, echo客户端能像下面这样处理并发读与写: 159 | 160 | ```rust 161 | use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 162 | use tokio::net::TcpStream; 163 | 164 | #[tokio::main] 165 | async fn main() -> io::Result<()> { 166 | let socket = TcpStream::connect("127.0.0.1:6124").await?; 167 | let (mut rd, mut wr) = io::split(socket); 168 | 169 | // 在后台写入数据 170 | let write_task = tokio::spawn(async move { 171 | wr.write_all(b"hello\r\n").await?; 172 | wr.write_all(b"world\r\n").await?; 173 | 174 | // 有时候Rust的推导需要一点帮助 175 | Ok::<_, io::Error>(()) 176 | }); 177 | 178 | let mut buf = vec![0; 128]; 179 | 180 | loop { 181 | let n = rd.read(&mut buf).await?; 182 | 183 | if n == 0 { 184 | break; 185 | } 186 | 187 | println!("GOT {:?}", &buf[..n]); 188 | } 189 | 190 | Ok(()) 191 | } 192 | ``` 193 | 194 | 因为 `io::split` 支持任意实现了`AsyncRead+AsyncWrite` 类型的值且返回独立的处理器, `io::split`内部使用了`Arc`与`Mutex`. 使用`TcpStream`可以避免这种开销, `TcpStream` 提供了两个专门的拆分函数. 195 | 196 | [TcpStream::split](https://docs.rs/tokio/0.2/tokio/net/struct.TcpStream.html#method.split) 引用流并返回一个reader和writer的处理器.因为使用了引用,所以两个处理器都必须保持与调用`split()`相同的任务一致. 这个特殊的`split`是零成本的. 这里不需要`Arc`或者`Mutex`. `TcpStream`也提供了一个 [into_split](https://docs.rs/tokio/0.2/tokio/net/struct.TcpStream.html#method.into_split) 功能,此功能支持仅需要`Arc`就能跨任务移动处理器. 197 | 198 | 因为`io::copy()`在属于`TcpStream`的同一个任务上被调用,所以我们可以使用 [TcpStream::split](https://docs.rs/tokio/0.2/tokio/net/struct.TcpStream.html#method.split).处理echo逻辑服务的任务变为: 199 | 200 | ```rust 201 | tokio::spawn(async move{ 202 | let(mut rd, mut wr) = socket.split(); 203 | 204 | if io::copy(&mut rd, &mut wr).await.is_err() { 205 | eprintln!("failed to copy"); 206 | } 207 | }); 208 | ``` 209 | 210 | 你可以 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/io/src/echo-server.rs) 找到完整的代码. 211 | 212 | ### 手动复制(Manual copying) 213 | 现在让我们来看看如何通过手动的复制数据来编写echo服务器. 为了做到这一点,我们使用 [AsyncReadExt::read](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncReadExt.html#method.read) 214 | 和 [AsyncWriteExt::write_all](https://docs.rs/tokio/0.2/tokio/io/trait.AsyncWriteExt.html#method.write_all) . 215 | 216 | 完整的echo服务像下面这样: 217 | 218 | ```rust 219 | use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 220 | use tokio::net::TcpListener; 221 | 222 | #[tokio::main] 223 | async fn main() -> io::Result<()> { 224 | let mut listener = TcpListener::bind("127.0.0.1:6124").await.unwrap(); 225 | 226 | loop { 227 | let (mut socket, _) = listener.accept().await?; 228 | 229 | tokio::spawn(async move { 230 | let mut buf = vec![0; 1024]; 231 | 232 | loop { 233 | match socket.read(&mut buf).await { 234 | // 返回 Ok(0) 值标识远程链接已关闭. 235 | Ok(0) => return, 236 | Ok(n) => { 237 | // 复制数据到socket中 238 | if socket.write_all(&buf[..n]).await.is_err() { 239 | // 未期待的socket错误, 这里我们不做什么,因此停止处理. 240 | return; 241 | } 242 | } 243 | Err(_) => { 244 | // 未期待的socket错误, 这里我们不做什么,因此停止处理. 245 | return; 246 | } 247 | } 248 | } 249 | }); 250 | } 251 | } 252 | ``` 253 | 254 | 让我们分解一下上面的过程. 首先, 由于使用了`AsyncRead`和`AsyncWrite`, 其扩展的trait必须要被引入到范围内. 255 | 256 | ```rust 257 | use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 258 | ``` 259 | 260 | (译者注: 上面有说过,我们仅能使用其扩展的trait) 261 | 262 | ### 分配一个缓冲区(Allocating a buffer) 263 | 有种策略是从socket中读取一些数据到buffer(缓冲区)中,然后将缓冲区的内容写回到socket中去. 264 | 265 | ```rust 266 | let mut buffer = vec![0;1024]; 267 | ``` 268 | 269 | 要明确的避免栈缓冲区. 回想一下 [之前的](./Spawning.md) (中的Send边界), 所有通过对`.await`调用存活的任务数据都必须由任务本身存储. 270 | 在这种情况下,将在`.await`的调用中使用`buf`. 所有的任务数据都被存储在一个分配中. 你可以将其看作一个枚举, 其中每个变量体都是为特定调用 271 | `.await`而需要存储的数据. 272 | 273 | 如果buffer由栈数组来表示, 那么每一个接受socket产生的任务的内部结构可能类似于: 274 | 275 | ```rust 276 | struct Task { 277 | // 内部的任务字段 278 | task: enum { 279 | AwaitingRead { 280 | socket: TcpStream, 281 | buf: [BufferType], 282 | }, 283 | AwaitingWriteAll { 284 | socket: TcpStream, 285 | buf: [BufferType], 286 | } 287 | 288 | } 289 | } 290 | ``` 291 | 292 | 如果栈数组被使用来作来buffer的类型, 它将以 _内联_ 的方式存储在任务结构中. 这将使用任务本身的结构变得非常大. 另外缓冲区buffer的大小通常是 293 | 页面大小. 反过来,这会使用任务(Task)大小变得很臃肿: `$page-size + a-few-bytes`. 294 | 295 | 编译器对异步结块布局的优化比基本的`enum`(枚举)更加好. 实际上,变量不会像枚举那样在变体中移动. 但是,任务结构体的大小至少与最大变量一样大. 296 | 297 | ### 处理 EOF(Handling EOF) 298 | (译者注: EOF: "end of file" 的缩写, 表示 "文字流结尾" 这种流(Stream) 可以是文件,也可以是标准输入. 一般理解为流的结束标识) 299 | 300 | 当读取TCP流的一半时关闭了, 调用`read()`会返回`Ok(0)`. 以这一点来退出循环是很重要的. 忘记以EOF标识来跳出循环是bug的常见来源方式. 301 | 302 | ```rust 303 | loop { 304 | match socket.read(&mut buffer).await { 305 | // 返回值是 Ok(0) 标志, 表示远端已经关闭 306 | Ok(0) => { 307 | // 其它处理 308 | } 309 | } 310 | } 311 | ``` 312 | 313 | 忘记以EOF标识来跳出循环的结果就是会造成CPU 100%循环占用. 关闭socket后, `socket.read()` 会立即返回. 然后循环会一直重复下去. 314 | 315 | 完整的代码参考 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/io/src/echo-server.rs) 316 | 317 | ← [通道(Channels)](Channels.md) 318 | 319 | → [帧(Framing)](Framing.md) -------------------------------------------------------------------------------- /doc/Introduction.md: -------------------------------------------------------------------------------- 1 | ## 指南(Tutorial) 2 | 这篇教程将一步步带你了解构建 [Redis](https://redis.io/) 客户端与服务端的过程. 我们将从使用Rust异步编程的基础开始. 我们将实现一个Redis 3 | 命令的子集并且获得关于Tokio的全方位的了解. 4 | 5 | ## 迷你-Redis(Mini-Redis) 6 | 你将在本教程中构建的工程可以在 [Mini-Redis on GitHub](https://github.com/tokio-rs/mini-redis) 上获得. Mini-Redis被设计的主要目的是 7 | 为了学习tokio,这种方式备受好评, 但这也意味着Mini-Redis缺少你想要的真实Redis库中的一些功能与特性. 你可以在这里 [crates.io](https://crates.io/) 8 | 上找到生产级可用Redis库. 9 | 10 | 我们将在本教程中直接使用Mini-Redis. 这使得我们在教程的后面实现部分之前,可以使用Mini-Redis的部分功能. 11 | 12 | ## 获取帮助(Getting Helping) 13 | 在任何时候, 如果你的学习被卡住, 你总能在 [Discord](https://discord.gg/tokio) 或 [Github discussions](https://github.com/tokio-rs/tokio/discussions) 上得到帮助. 14 | 不必担心问一些 **"初学者"** 问题. 我们都是从某个地方开始的,并且乐于提供帮助. 15 | 16 | ## 前提条件(Prerequisites) 17 | 读者应该已经熟悉了 [Rust](https://rust-lang.org/) . [Rust book](https://doc.rust-lang.org/book/) 是入门的绝佳资源. 18 | 19 | 虽然不是必须的, 但是你有Rust标准库或其它语言编写网络代码的一些经验的话,那将会有所帮助. 20 | 21 | Redis相关的知识不是必要的. 22 | 23 | ## Rust 24 | 在我们开始之前, 你应该确保你已安装了 [Rust](https://www.rust-lang.org/tools/install) 工具链并做好了准备. 如果你没有做好这些, 使用 25 | [rustup](https://rustup.rs/) 来安装是一个很好的方式. 26 | 27 | 本教程需要的最小Rust版本是 `1.39.0` , 但是推荐最好是最近的 Rust stable 版本. 28 | 29 | 为了检查Rust已经安装到你的电脑上, 执行如下命令查看: 30 | 31 | ```shell script 32 | rustc --version 33 | ``` 34 | 你应该会看到像 `rustc 1.43.1 (8d69840ab 2020-05-04)` 这样的输出. 35 | 36 | ## 迷你Redis服务(Mini-Redis server) 37 | 接下来安装Mini-Redis 服务. 它被用来测试我们即将要构建的客户端. 38 | ```shell script 39 | cargo install mini-redis 40 | ``` 41 | 执行下面的命令确保服务启动与安装成功了: 42 | ```shell script 43 | mini-redis-server 44 | ``` 45 | 然后尝试使用 `mini-redis-cli` 来得到键 `foo` 的值: 46 | ```shell script 47 | mini-redis-cli get foo 48 | ``` 49 | 你应该会看了 `nil` . 50 | 51 | ## 准备开始(Ready to go) 52 | 现在一切都作好了准备. 去到下一章节你将编写你的第一个Rust异步应用. 53 | 54 | → [你好 Tokio](HelloTokio.md) 55 | 56 | 57 | -------------------------------------------------------------------------------- /doc/Select.md: -------------------------------------------------------------------------------- 1 | ## Select 2 | 到目前为止,当我们想向系统添加并发时,我们会产生一个新的任务(task). 现在我们将介绍使用Tokio来并发执行异步代码的其它方法. 3 | 4 | ## `tokio::select!` 5 | `tokio::select!` 宏允许等待多个异步计算且当单个计算完成时返回(译者注: 多个并发或并行异步计算任务,返回最先完成的那个). 6 | 7 | 比如说: 8 | 9 | ```rust 10 | use tokio::sync::oneshot; 11 | 12 | #[tokio::main] 13 | async fn main() { 14 | let (tx1, rx1) = oneshot::channel(); 15 | let (tx2, rx2) = oneshot::channel(); 16 | 17 | tokio::spawn(async { 18 | let _ = tx1.send("one"); 19 | }); 20 | 21 | tokio::spawn(async { 22 | let _ = tx2.send("two"); 23 | }); 24 | 25 | tokio::select! { 26 | val = rx1 => { 27 | println!("rx1 completed first with {:?}", val); 28 | } 29 | val = rx2 => { 30 | println!("rx2 completed first with {:?}", val); 31 | } 32 | } 33 | } 34 | ``` 35 | 36 | 使用了两个 `oneshot` 通道. 其中任一通道都能先完成. `select!` 语句在两个channels上等待,并将`va1`绑定到任务返回的值上. 当其中任一 `tx1` 或者 37 | `tx2` 完成时,与之相关的块就会执行. 38 | 39 | 另外没有被完成的分支将会被丢弃(dropped). 在上面的示例中,计算正在每个channel的 `oneshot::Receiver` 上等待. 没有完成的`oneshot::Receiver` 40 | channel将会被丢弃. 41 | 42 | ### 取消(Cancellation) 43 | 对于异步Rust来说,取消操作是通过删除一个future来完成的. 回顾一下 [深入异步](AsyncInDepth.md) 章节中,使用future来实现Rust的异步操作且 44 | future是惰性的. 仅仅当future被轮询时操作才会处理. 如果future被删除(丢弃),操作就不会继续,因为与之所有相关联的状态都被丢弃了. 45 | 46 | 也说是说,有时候异步操作将产生后台任务或者启动在后台运行的其它操作. 比方说,在上面的示例中,产生一个任务将消息发送回去. 一般来说这个任务会执行 47 | 一些计算来生成值. 48 | 49 | Futures或者其它类型能通过实现 `Drop` 去清理后台资源. Tokio的`oneshot::Receiver`通过向`Sender`方发送一个关闭的通知来实现`Drop`功能. 50 | Sender方能接收到这个通知并通过丢弃正在进行的操作来中止它. 51 | 52 | ```rust 53 | use tokio::sync::oneshot; 54 | 55 | async fn some_operation() -> String { 56 | // 这里计算值 57 | } 58 | 59 | #[tokio::main] 60 | async fn main() { 61 | let (mut tx1, rx1) = oneshot::channel(); 62 | let (tx2, rx2) = oneshot::channel(); 63 | 64 | tokio::spawn(async { 65 | // select 操作和 oneshot 的 `close()` 通知. 66 | tokio::select! { 67 | val = some_operation() => { 68 | let _ = tx1.send(val); 69 | } 70 | _ = tx1.closed() => { 71 | // `some_operation()` 被调用, 72 | // 任务完成且 `tx1` 被丢弃 73 | } 74 | } 75 | }); 76 | 77 | tokio::spawn(async { 78 | let _ = tx2.send("two"); 79 | }); 80 | 81 | tokio::select! { 82 | val = rx1 => { 83 | println!("rx1 completed first with {:?}", val); 84 | } 85 | val = rx2 => { 86 | println!("rx2 completed first with {:?}", val); 87 | } 88 | } 89 | } 90 | ``` 91 | 92 | ### `Future`的实现(The `Future` implementation) 93 | 为了帮助更好的理解`select!`是如何工作的,让我们看看假想的Future实现像什么样子. 这是一个简单的版本. 在具体的实践中,`select!`还包括其它的功能, 94 | 比如随机选择要首先轮询的分支. 95 | 96 | ```rust 97 | use tokio::sync::oneshot; 98 | use std::future::Future; 99 | use std::pin::Pin; 100 | use std::task::{Context, Poll}; 101 | 102 | struct MySelect { 103 | rx1: oneshot::Receiver<&'static str>, 104 | rx2: oneshot::Receiver<&'static str>, 105 | } 106 | 107 | impl Future for MySelect { 108 | type Output = (); 109 | 110 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { 111 | if let Poll::Ready(val) = Pin::new(&mut self.rx1).poll(cx) { 112 | println!("rx1 completed first with {:?}", val); 113 | return Poll::Ready(()); 114 | } 115 | 116 | if let Poll::Ready(val) = Pin::new(&mut self.rx2).poll(cx) { 117 | println!("rx2 completed first with {:?}", val); 118 | return Poll::Ready(()); 119 | } 120 | 121 | Poll::Pending 122 | } 123 | } 124 | 125 | #[tokio::main] 126 | async fn main() { 127 | let (tx1, rx1) = oneshot::channel(); 128 | let (tx2, rx2) = oneshot::channel(); 129 | 130 | // use tx1 and tx2 131 | 132 | MySelect { 133 | rx1, 134 | rx2, 135 | }.await; 136 | } 137 | ``` 138 | `MySelect` future 包含每个分支的future. 当`MySelect`被轮询时,第一个分支被轮询. 如果它是ready状态,就使用它的值且`MySelect`完成. 139 | 然后`.await`接收到来着future的输出,future被删除. 结果就是两个分支的future都被删除. 因为一个分支未完成,因此操作被有效取消. 140 | 141 | 记住来自上一章节的话: 142 | 143 | ```markdown 144 | 当一个future返回Poll::Pending时,它**必须**确保在future的某个时候向waker发送信号. 忘记这样做会导致任务无限被挂起. 145 | ``` 146 | 147 | `MySelect`的实现中没有显示的使用`Context`的参数. 取代的是,通过将`cx`传递给内部future来满足waker的要求. 由于内部future也必须满足waker的 148 | 要求,因此在收到来自内部future的`Poll::Pending`时仅返回`Poll::Pending`. 所以`MySelect`也满足waker的要求. 149 | 150 | ## 语法(Syntax) 151 | `select!`宏能处理超过2个以上的分支. 当前最大限制64个分支. 每个分支的结构像下面这样: 152 | 153 | ```text 154 | = => , 155 | ``` 156 | 157 | 当`select!`宏展开时,所有的``都会被汇总并同时执行. 当其中一个表达式完成时,结果就会被匹配到``. 如果结果与 158 | pattern匹配时,那么将删除所有剩余的异步表达式并执行``. ``表达式可以访问被``建立的任何绑定值. 159 | 160 | 基本上``就是变量名,异步表达式的结果可以绑定到这个变量名上且``可以访问这个变量. 这就是为什么最开始的示例中,`va1`能被 161 | ``使用且``能访问`va1`. 162 | 163 | 如果``与异步计算的结果不匹配,则其余的异步表达式将继续并发执行直到下一个完成为止. 这时,将相同的逻辑用于该结果. 164 | 165 | 因为`select!`可以采用任意的异步表达式,所以可以在定义复杂的计算时来选择它. 166 | 167 | 在这里,我们选择`oneshot` channel和TCP链接的输出. 168 | 169 | ```rust 170 | use tokio::net::TcpStream; 171 | use tokio::sync::oneshot; 172 | 173 | #[tokio::main] 174 | async fn main() { 175 | let (tx, rx) = oneshot::channel(); 176 | 177 | // 产生一个任务来发送消息到oneshot 中 178 | tokio::spawn(async move { 179 | tx.send("done").unwrap(); 180 | }); 181 | 182 | tokio::select! { 183 | socket = TcpStream::connect("localhost:3465") => { 184 | println!("Socket connected {:?}", socket); 185 | } 186 | msg = rx => { 187 | println!("received message first {:?}", msg); 188 | } 189 | } 190 | } 191 | ``` 192 | 193 | 在这里,我们选择一个`oneshot`并接收来自`TcpListener`的socket套接字. 194 | 195 | ```rust 196 | use tokio::net::TcpListener; 197 | use tokio::sync::oneshot; 198 | use std::io; 199 | 200 | #[tokio::main] 201 | async fn main() -> io::Result<()> { 202 | let (tx, rx) = oneshot::channel(); 203 | 204 | tokio::spawn(async move { 205 | tx.send(()).unwrap(); 206 | }); 207 | 208 | let mut listener = TcpListener::bind("localhost:3465").await?; 209 | 210 | tokio::select! { 211 | _ = async { 212 | loop { 213 | let (socket, _) = listener.accept().await?; 214 | tokio::spawn(async move { process(socket) }); 215 | } 216 | 217 | // 帮助Rust的类型推导 218 | Ok::<_, io::Error>(()) 219 | } => {} 220 | _ = rx => { 221 | println!("terminating accept loop"); 222 | } 223 | } 224 | 225 | Ok(()) 226 | } 227 | ``` 228 | 229 | accept循环一直运行,直到遇到错误或`rx`接到到值为止. `_`表示我们对异步计算返回的值不感兴趣. 230 | 231 | ## 返回值(Return value) 232 | `tokio::select!`宏返回``表达式的结果. 233 | 234 | ```rust 235 | async fn computation1() -> String { 236 | // 计算1 237 | } 238 | 239 | async fn computation2() -> String { 240 | // 计算2 241 | } 242 | 243 | #[tokio::main] 244 | async fn main() { 245 | let out = tokio::select! { 246 | res1 = computation1() => res1, 247 | res2 = computation2() => res2, 248 | }; 249 | 250 | println!("Got = {}", out); 251 | } 252 | ``` 253 | 254 | 因为这一点,它需要``表达式每个分支返回的值相同. 如果`select!`表达式的输出不是必须的,推荐将表达式的返回值类型为 `()`. 255 | 256 | ## 错误(Errors) 257 | 使用`?`号操作符从表达式传播错误. 它如何工作是取决于是否`?`号从异步表达式或处理程序中使用. 使用`?`在异步表达式中能将错误传播到异步表达式之外. 258 | 这就使异步表达式的输出成一个`Result`了. 从一个处理程序使用`?`号能立即传播错误到`select!`表达式之外. 让我们再次来看看accept 循环: 259 | 260 | ```rust 261 | use tokio::net::TcpListener; 262 | use tokio::sync::oneshot; 263 | use std::io; 264 | 265 | #[tokio::main] 266 | async fn main() -> io::Result<()> { 267 | // [设置 `rx` oneshot channel] 268 | let listener = TcpListener::bind("localhost:3465").await?; 269 | 270 | tokio::select! { 271 | res = async { 272 | loop { 273 | let (socket, _) = listener.accept().await?; 274 | tokio::spawn(async move { process(socket) }); 275 | } 276 | 277 | // 帮助Rust类型推导 278 | Ok::<_, io::Error>(()) 279 | } => { 280 | res?; 281 | } 282 | _ = rx => { 283 | println!("terminating accept loop"); 284 | } 285 | } 286 | 287 | Ok(()) 288 | } 289 | ``` 290 | 291 | 注意`listener.accept().await?`. `?`号操作符传播错误到表达式之外且和`res`绑定. 如果是一个错误, `res`将被设置为`Err(_)`. 当然在handler内部 292 | `?`可以再次使用. `res?` 声明将传播一个错误到`main`函数之外. 293 | 294 | ## 模式匹配(Pattern matching) 295 | 回顾一下`select!`宏的分支语法定义: 296 | 297 | ```text 298 | = = , 299 | ``` 300 | 301 | 到目前为止,我们仅仅对``使用了变量绑定. 然而,这里能使用任何Rust模式. 比如说,假设我们从多个 MPSC 通道接收,我们可能会执行以下操作: 302 | 303 | ```rust 304 | use tokio::sync::mpsc; 305 | 306 | #[tokio::main] 307 | async fn main() { 308 | let (mut tx1, mut rx1) = mpsc::channel(128); 309 | let (mut tx2, mut rx2) = mpsc::channel(128); 310 | 311 | tokio::spawn(async move { 312 | // Do something w/ `tx1` and `tx2` 313 | }); 314 | 315 | tokio::select! { 316 | Some(v) = rx1.recv() => { 317 | println!("Got {:?} from rx1", v); 318 | } 319 | Some(v) = rx2.recv() => { 320 | println!("Got {:?} from rx2", v); 321 | } 322 | else => { 323 | println!("Both channels closed"); 324 | } 325 | } 326 | } 327 | ``` 328 | 329 | 在这个例子中,`select!`表达式等待从`rx1`和`rx2`接收值. 如果一个channel关闭了,`recv()`返回了`None`. 这与模式不匹配且分支会被禁用. 330 | `select!`表达将继续在其它分支上等待. 331 | 332 | 注意`select!`表达式包含了一个`else`分支. `select!`表达式必须返回一个值. 在使用模式匹配时,可能所有的分支都不能匹配上关联的模式. 如果这种 333 | 情况发生了,那么`else`分支将会被返回. 334 | 335 | ## 借用(Borrowing) 336 | 当产生一个任务时,生成的异步表达式必须要有其所有的数据. `select!`宏没有这样的限制. 每一个分支的数据都能借用数据并同时进行操作. 根据Rust的 337 | 借用规则来看,多个异步表达式可以,**不可变**的借用单个数据,或者单个异步表达式可以**可变**的借用数据. 338 | 339 | 让我们来看一些例子. 在这里,我们同时将相同的数据发送到两个不同的TCP目标上. 340 | 341 | ```rust 342 | use tokio::io::AsyncWriteExt; 343 | use tokio::net::TcpStream; 344 | use std::io; 345 | use std::net::SocketAddr; 346 | 347 | async fn race( 348 | data: &[u8], 349 | addr1: SocketAddr, 350 | addr2: SocketAddr 351 | ) -> io::Result<()> { 352 | tokio::select! { 353 | Ok(_) = async { 354 | let mut socket = TcpStream::connect(addr1).await?; 355 | socket.write_all(data).await?; 356 | Ok::<_, io::Error>(()) 357 | } => {} 358 | Ok(_) = async { 359 | let mut socket = TcpStream::connect(addr2).await?; 360 | socket.write_all(data).await?; 361 | Ok::<_, io::Error>(()) 362 | } => {} 363 | else => {} 364 | }; 365 | 366 | Ok(()) 367 | } 368 | ``` 369 | 370 | 这两个异步表达式中都是**不可变**的借用了`data`变量. 当其中一个操作成功完成后,另外一个将被丢弃. 因为我们在`Ok()`上进行了模式匹配,如果一个表达式 371 | 失败,另外一个将继续执行. 372 | 373 | 当涉及到每个分支的``时,`select!`保证只有一个``运行. 根据这一点,每一个``可以**可变**的借用同一个数据. 374 | 375 | 例如,修改下两个handlers: 376 | 377 | ```rust 378 | use tokio::sync::oneshot; 379 | 380 | #[tokio::main] 381 | async fn main() { 382 | let (tx1, rx1) = oneshot::channel(); 383 | let (tx2, rx2) = oneshot::channel(); 384 | 385 | let mut out = String::new(); 386 | 387 | tokio::spawn(async move { 388 | // 在 tx1和tx2上发送值 389 | }); 390 | 391 | tokio::select! { 392 | _ = rx1 => { 393 | out.push_str("rx1 completed"); 394 | } 395 | _ = rx2 => { 396 | out.push_str("rx2 completed"); 397 | } 398 | } 399 | 400 | println!("{}", out); 401 | } 402 | ``` 403 | 404 | ## 循环(Loops) 405 | `select!`宏经常在循环中使用. 本节将介绍一些示例,来展示在循环中使用`select!`的常用方法. 我们首先使用 multiple channels: 406 | 407 | ```rust 408 | use tokio::sync::mpsc; 409 | 410 | #[tokio::main] 411 | async fn main() { 412 | let (tx1, mut rx1) = mpsc::channel(128); 413 | let (tx2, mut rx2) = mpsc::channel(128); 414 | let (tx3, mut rx3) = mpsc::channel(128); 415 | 416 | loop { 417 | let msg = tokio::select! { 418 | Some(msg) = rx1.recv() => msg, 419 | Some(msg) = rx2.recv() => msg, 420 | Some(msg) = rx3.recv() => msg, 421 | else => { break } 422 | }; 423 | 424 | println!("Got {}", msg); 425 | } 426 | 427 | println!("All channels have been closed."); 428 | } 429 | ``` 430 | 431 | 上面的示例选择了3个channel的接收器(receiver). 在任何通道上接收消息时,它将被写入到STDOUT. 当一个channel关闭时,`recv()`会返回`None`. 432 | 通过使用模式匹配,`select!`宏会继续在其它channel上等待. 当所有的通道都关闭了,`else`分支会被匹配且循环被终止. 433 | 434 | `select!`宏会随机的选择分支来首先枪柄就绪情况. 当多个通道都有待定的值时,将从其中随机选择一个来接收. 这是为了处理接收循环处理消息的速度慢于将消息 435 | 推送到通道中的情况,这意味着通道填充数据. 如果`select!`没有随机的选择首先要检查的分支,那么在每次循环迭代中,将首先检查`rx1`. 如果`rx1` 436 | 始终都有新消息,则永远不会再检查其余的通道了. 437 | 438 | ```markdown 439 | 如果当`select!`被评估时,多个通道都有待处理的消息,只会弹出(pop)一个通道的值. 所有其它的通道保持不变,它们的消息会保留在这些通道中,直到下一次循环迭代为止. 不会有消息丢失. 440 | ``` 441 | 442 | ### 恢复异步操作(Resuming an async operation) 443 | 444 | 现在,我们将展示如何在多个`select!`调用之间运行异步操作! 在这个示例当中,我们使用一个类型为`i32`的 MPSC channel,并且它是异步的. 我们要运行异步函数,直到它完成或在接收到偶数整数为止. 445 | 446 | ```rus 447 | async fn action() { 448 | // 一些异步逻辑 449 | } 450 | 451 | #[tokio::main] 452 | async fn main() { 453 | let (mut tx, mut rx) = tokio::sync::mpsc::channel(128); 454 | 455 | let operation = action(); 456 | tokio::pin!(operation); 457 | 458 | loop { 459 | tokio::select! { 460 | _ = &mut operation => break, 461 | Some(v) = rx.recv() => { 462 | if v % 2 == 0 { 463 | break; 464 | } 465 | } 466 | } 467 | } 468 | } 469 | ``` 470 | 471 | 注意如何,而不是在`select!`宏中调用`action()`, 它在循环外被调用. `action()`的返回分配给`operation`,而不需要调用`.await`.然后我们在`operation`上调用 472 | 473 | `tokio::pin!`. 474 | 475 | 在`select!`循里面,不是传递`operation`而是传递`&mut operation`. `operation`变量正在跟踪异步操作. 循环中的每一次迭代都使用相同的操作,而不是发出对`action()`的一次新的调用. 476 | 477 | 其它的`select!`分支从通道中接收消息. 如果消息是偶数,则循环完成. 否则再次开始 `select!`. 478 | 479 | 这里我们第一次使用了`tokio::pin!`. 我们暂时不去讨论pin的细节. 需要注意的是,为了`.await`一个引用,必须固定引用的值或者实现`Unpin`. 480 | 481 | 如果我们移除`tokio::pin!`这一行并再去尝试编译,我们会得到下面的错误: 482 | 483 | ```text 484 | error[E0599]: no method named `poll` found for struct 485 | `std::pin::Pin<&mut &mut impl std::future::Future>` 486 | in the current scope 487 | --> src/main.rs:16:9 488 | | 489 | 16 | / tokio::select! { 490 | 17 | | _ = &mut operation => break, 491 | 18 | | Some(v) = rx.recv() => { 492 | 19 | | if v % 2 == 0 { 493 | ... | 494 | 22 | | } 495 | 23 | | } 496 | | |_________^ method not found in 497 | | `std::pin::Pin<&mut &mut impl std::future::Future>` 498 | | 499 | = note: the method `poll` exists but the following trait bounds 500 | were not satisfied: 501 | `impl std::future::Future: std::marker::Unpin` 502 | which is required by 503 | `&mut impl std::future::Future: std::future::Future` 504 | ``` 505 | 506 | 这个错误不是很清晰,我们也没有讨论太多的关于`Future`的信息. 现在将`Future`看作必须通过一什值实现才能调用`.await`的trait. 如果在尝试对引用调用`.await`时遇到了有关没有实现`Future`的错误时,则可能需要固定住`Future`. 507 | 508 | 有关标准库中`Pin`更多的细节可以查看[Pin](https://doc.rust-lang.org/std/pin/index.html). 509 | 510 | ### 修改一个分支(Modifying a branch) 511 | 512 | 让我们看看一个稍微复杂的循环. 我们有: 513 | 514 | 1. `i32`值的通道. 515 | 2. 对`i321值执行的异步操作. 516 | 517 | 我们想实现的逻辑是: 518 | 519 | 1. 在channel上等待一个偶数. 520 | 2. 使用偶数作为输入启动异步操作. 521 | 3. 等待操作,但同时在channel上监听更多的偶数. 522 | 4. 如果在现有操作完成之前接收到了新的偶数,要中止现在操作,并使用新的偶数重新开始. 523 | 524 | ```rust 525 | async fn action(input: Option) -> Option { 526 | // 如果输None则返回None 527 | // 也可以写成 let i = input?;` 528 | let i = match input { 529 | Some(input) => input, 530 | None => return None, 531 | }; 532 | // 这里是异步逻辑 533 | } 534 | 535 | #[tokio::main] 536 | async fn main() { 537 | let (mut tx, mut rx) = tokio::sync::mpsc::channel(128); 538 | 539 | let mut done = false; 540 | let operation = action(None); 541 | tokio::pin!(operation); 542 | 543 | tokio::spawn(async move { 544 | let _ = tx.send(1).await; 545 | let _ = tx.send(3).await; 546 | let _ = tx.send(2).await; 547 | }); 548 | 549 | loop { 550 | tokio::select! { 551 | res = &mut operation, if !done => { 552 | done = true; 553 | 554 | if let Some(v) = res { 555 | println!("GOT = {}", v); 556 | return; 557 | } 558 | } 559 | Some(v) = rx.recv() => { 560 | if v % 2 == 0 { 561 | // .set 是在 Pin 上的一个方法 562 | operation.set(action(Some(v))); 563 | done = false; 564 | } 565 | } 566 | } 567 | } 568 | } 569 | ``` 570 | 我们使用了与之前例子类似的策略. 异步函数在循环外部被调用并分配给`operation`变量. `operation`变量被固定. 循环同时在`operation`与通道接收在选择(select). 571 | 572 | 注意到,`action()`是怎样传入一个`Option`参数的,在我们收到第一个偶整数之前,我们必须实例化一些`operation`. 我们让`action()`传入`Option`并返回`Option`. 573 | 如果传入的是`None`就返回`None`. 第一次迭代,`operation`立即完成,并显示`None`. 574 | 575 | 这个示例使用了一些新语法. 第一个分支包含`, if !done`. 这是分支的前提. 在解释其工作原理之前,让我们看一下如果省略了前提条件会发生什么. 576 | 省略`, if !done` 并运行示例会得到如下输出结果: 577 | 578 | ```text 579 | thread 'main' panicked at '`async fn` resumed after completion', src/main.rs:1:55 580 | note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace 581 | ``` 582 | 583 | 当尝试在`operation`完成之后再去使用它,就会发生此错误. 通常,在使用`.await`时,等待的值会被消费. 在这个例子中我们在一个引用上等待. 584 | 这意味着`operation`完成之后它任然存在. 585 | 586 | 为了避免这种panic,如果`operation`完成了,我们必须注意禁用第一个分支. `done`变量用于跟踪`operation`是否完成. 一个`select!`分支可以包含 587 | 一个前提条件. `select!`在分支上等待之前该前提条件会被检查. 如果前提条件的评估结果是`false`,则禁用分支. `done`变量被初始化为`false`. 588 | 当`operation`完成后,`done`被设置为`true`. 下一次循环迭代将禁用`operation`分支. 当从channel中接收到偶数时,`operation`会被重置且 589 | `done`再次被设置为 `false`. 590 | 591 | ## 每个任务的并发(Per-task concurrency) 592 | `tokio::spawn` 与 `select!` 都可以运行并发异步操作. 但是用于运行并发操作的策略有所不同. `tokio::spawn` 函数传入一个异步操作并产生一个 593 | 新的任务去运行它. 任务是一个tokio运行时调度的对象. Tokio独立调度两个不同的任务. 它们可以在不同的操作系统线程上同时运行. 因此产生的任务与 594 | 产生的线程都有相同的限制: 不可借用. 595 | 596 | `select!`宏能在同一个任务上同时运行所有分支. 因为`select!`宏上的所有分支被同一个任务执行,它们永远不会同时运行. `select!`宏的多路复用 597 | 异步操作也在单个任务上运行. 598 | 599 | 600 | ← [深入异步(Async in depth)](AsyncInDepth.md) 601 | 602 | → [流(Streams)](Streams.md) 603 | 604 | 605 | 606 | 607 | -------------------------------------------------------------------------------- /doc/SharedState.md: -------------------------------------------------------------------------------- 1 | ## 共享状态(Shared state) 2 | 到目前为止, 我们有了一个能工作的键值对服务. 然后, 这里有一个主要的缺陷: 状态不能在链接之间共享. 因此我们将在这篇文章中修复这个问题. 3 | 4 | ## 策略(Strategies) 5 | 在Tokio中共享状态有两种不同的方法. 6 | 1. 使用Mutex(互斥锁)保护共享状态. 7 | 2. 产生一个任务来管理状态并使用消息传递对其进行操作. 8 | 9 | 通常来说你想使用第一种方试来处理简单的数据, 对于需要异步工作的事务(比如 I/O 原语)应该使用第二种方试. 在本章节中, 共享状态是一个 `HashMap` 10 | 并使用 `insert` 与 `get` 来操作. 这些操作都不是异步的,因此我们使用 `Mutex` . 11 | 12 | 下一章节将介绍另外一种方法. 13 | 14 | ## 添加 `bytes` 依赖(Add `bytes` dependency) 15 | Mini-Redis包使用 `bytes` 包中的 `Bytes` 类型, 而不是使用 `Vec` . `Bytes` 的目的是为网络编程提供一个健全的字节数组结构. 它在 16 | `Vec` 上添加的最大功能是浅克隆. 换句话说, 在 `Bytes` 的实例上调用 `clone()` 方法不会复制底层的数据. 相反 `Bytes` 实例是对一些 17 | 底层数据的引用计数. `Bytes` 类型大致与一个 `Arc>` 类似, 但还添加了一些其它功能. 18 | 19 | 为了依赖 `bytes` , 在你的 `Cargo.toml` 文件中的 `[dependencies]` 下添加如下内容: 20 | ```toml 21 | bytes = "0.5" 22 | ``` 23 | 24 | ## 初始化 `HashMap` (Initialize the `HashMap` ) 25 | `HashMap` 会在许多任务和可能的许多线程之间共享. 为了支持这一点, 它被包装在 `Arc>` 中. 26 | 27 | 首先, 为了方便,使用 `use` 声明添加如下类型的别名. 28 | 29 | ```rust 30 | use bytes::Bytes; 31 | use std::collections::HashMap; 32 | use std::sync::{Arc, Mutex}; 33 | 34 | type Db = Arc>>; 35 | ``` 36 | 37 | 然后更新 `main` 函数来初始化是 `HashMap` 并传递 `Arc` 句柄给 `process` 函数. 使用 `Arc` 可以同时从许多任务中引用 `HashMap` , 这些 38 | `HashMap` 也可能在许多线程上运行. 在整个Tokio中, 术语 **Handle** (这里译为 **句柄**)用于引用提供对某些共享状态访问的值. 39 | 40 | ```rust 41 | use tokio::net::TcpListener; 42 | use std::collections::HashMap; 43 | use std::sync::{Arc, Mutex}; 44 | 45 | #[tokio::main] 46 | async fn main() { 47 | let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); 48 | 49 | println!("Listening"); 50 | 51 | let db = Arc::new(Mutex::new(HashMap::new())); 52 | 53 | loop { 54 | let (socket, _) = listener.accept().await.unwrap(); 55 | // Clone the handle to the hash map. 56 | let db = db.clone(); 57 | 58 | println!("Accepted"); 59 | process(socket, db).await; 60 | } 61 | } 62 | ``` 63 | 64 | 注意, 这里使用的是 `std::sync::Mutex` 来保护 `HashMap` 并不是 `tokio::sync::Mutex` . 一个常见的错误是在异步代码中无条件的使用 65 | `tokio::sync::Mutex` . 异步的 mutex 是一种通过调用 `.await` 来锁定的互斥锁. 66 | 67 | 同步的mutex会等待获取这把锁时阻塞当前线程. 反过来, 将阻止其它任务的处理. 然而, 换成 `tokio::sync::Mutex` 通常无济于事, 是因为异步mutex 68 | 在内部使用同步互斥锁. 根据经验, 只要锁竞争保持在低水平且在对 `.await` 的调用中不持有锁, 则可以在异步代码中使用同步互斥锁. 另外可以考虑使用 69 | `parking_log::Mutex` 作为 `std::sync::Mutex` 更快的替代方案. 70 | 71 | ## 更新 `process()` (Update `process()`) 72 | `process()` 函数不再初始化一个 `HashMap` . 取而代之的是, 它将 `HashMap` 的共享句柄作为一个参数传进去. 在使用它之前还需要锁定 `HashMap` . 73 | 74 | ```rust 75 | use tokio::net::TcpStream; 76 | use mini_redis::{connection, Frame}; 77 | 78 | async fn process(socket: TcpStream, db: Db) { 79 | use mini_redis::Command::{self, Get, Set}; 80 | 81 | // 通过 mini-redis 提供 connection , 用来处理解析 socket中的帧 82 | let mut connection = connection::new(socket); 83 | 84 | while let Some(frame) = connection.read_frame().await.unwrap() { 85 | let response = match Command::from_frame(frame).unwrap() { 86 | Set(cmd) => { 87 | let mut db = db.lock().unwrap(); 88 | db.insert(cmd.key().to_string(), cmd.value().clone()); 89 | Frame::Simple("OK".to_string()) 90 | } 91 | Get(cmd) => { 92 | let db = db.lock().unwrap(); 93 | if let Some(value) = db.get(cmd.key()) { 94 | Frame::Bulk(value.clone()) 95 | } else { 96 | Frame::Null 97 | } 98 | } 99 | cmd => panic!("unimplemented {:?}", cmd), 100 | }; 101 | 102 | // 写回响应到客户端 103 | connection.write_frame(&response).await.unwrap(); 104 | } 105 | } 106 | ``` 107 | 108 | ## 任务,线程与竞争(Tasks, threads, and contention) 109 | 当竞争不激烈(很小)的时候, 使用阻塞的互斥锁来保护关键的部分是一种可接受的策略. 当去竞争锁时,执行任务的线程必须阻塞等待互斥锁. 这不仅会阻塞 110 | 当前任务, 还将阻塞当前线程上调度的所有其它任务. 111 | 112 | 默认情况下, Tokio运行时使用多线程的调度器. 任务可以被任何一个运行时管理的线程调度. 如果有大量的任务被调度去执行且它们都需要访问互斥锁, 113 | 这个时候就存在锁竞争. 反过来说, 如果使用 [current_thread](https://docs.rs/tokio/0.3/tokio/runtime/index.html#current-thread-scheduler) 则互斥锁不会被竞争. 114 | 115 | ```markdown 116 | `current_thread` 是一个轻量级, 单线程的**运行时**, 当仅需要产生一些任务并打开少数socket时,这是一个不错的选择. 比如说, 当提供一个同步API桥接在一个异步客户端库顶部时, 此选项很好用. 117 | ``` 118 | 119 | 如果在同步互斥锁上的竞争有问题时, 最好的解决办法就是少量切换到Tokio的互斥锁. 相反要考虑的选项是: 120 | * 切换到专用任务来管理状态和使用消息传递机制. 121 | * 分割互斥锁(译者注: 类似分段锁机制). 122 | * 重构代码避免互斥锁. 123 | 124 | 在我们的案例中, 每一个 _key_ 都是独立的, 所以互斥锁可以很好的工作. 因此,我们将用 `N` 个不同的实例, 而不是使用单个 `Mutex` 实例. 125 | 126 | ```rust 127 | type ShardedDb = Arc>>>>; 128 | ``` 129 | 130 | 然后, 根据任何给定的键查找到值是两步过程. 首先, key 用来识别它是哪一部分. 然后, 在 `HashMap` 中查找key的值. 131 | 132 | ```rust 133 | let shard = db[hash(key) % db.len()].lock().unwrap(); 134 | shard.insert(key, value); 135 | ``` 136 | 137 | (译者注: 这种分段锁思想与jdk1.8之前的ConcurrentHashMap底层实现一样). 138 | 139 | [dashmap](https://docs.rs/dashmap) 包提供了分段hash map 实现. 140 | 141 | ## 通过 `.await` 来持有一个 `MutexGuard` (Holding a `MutexGuard` across an `.await` ) 142 | 你可能写像下面这样的代码: 143 | 144 | ```rust 145 | use std::sync::Mutex; 146 | 147 | async fn increment_and_do_stuff(mutex: &Mutex) { 148 | let mut lock = mutex.lock().unwrap(); 149 | *lock += 1; 150 | do_something_async().await; 151 | } // lock 在这里超出作用域范围 152 | ``` 153 | 154 | 当你尝试生成调用此函数的内容时, 会遇到以下的错误消息: 155 | 156 | ```text 157 | error: future cannot be sent between threads safely 158 | --> src/lib.rs:13:5 159 | | 160 | 13 | tokio::spawn(async move { 161 | | ^^^^^^^^^^^^ future created by async block is not `Send` 162 | | 163 | ::: /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.21/src/task/spawn.rs:127:21 164 | | 165 | 127 | T: Future + Send + 'static, 166 | | ---- required by this bound in `tokio::task::spawn::spawn` 167 | | 168 | = help: within `impl std::future::Future`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard<'_, i32>` 169 | note: future is not `Send` as this value is used across an await 170 | --> src/lib.rs:7:5 171 | | 172 | 4 | let mut lock = mutex.lock().unwrap(); 173 | | -------- has type `std::sync::MutexGuard<'_, i32>` which is not `Send` 174 | ... 175 | 7 | do_something_async().await; 176 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^ await occurs here, with `mut lock` maybe used later 177 | 8 | } 178 | | - `mut lock` is later dropped here 179 | ``` 180 | 181 | 发生这的原因是, `std::sync::MutexGuard` 类型不是 `Send` . 这意味着你不能够发送一个互斥锁到另外一个线程中, 并且会发生错误, 因为Tokio 182 | 运行时可以在每个 `.await` 的线程之间移动任务. 为了避免这种情况, 你需要重组代码来使互斥锁的析构函数在 `.await` 之前运行. 183 | 184 | ```rust 185 | use std::sync::Mutex; 186 | // 这是可以的! 187 | async fn increment_and_do_stuff(mutex: &Mutex) { 188 | { 189 | let mut lock = mutex.lock().unwrap(); 190 | *lock += 1; 191 | }// lock 在这里超出作用域范围 192 | do_something_async().await; 193 | } 194 | ``` 195 | 196 | 注意下面这种无法工作: 197 | 198 | ```rust 199 | use std::sync::Mutex; 200 | 201 | // 这也会失败 202 | async fn increment_and_do_stuff(mutex: &Mutex) { 203 | let mut lock = mutex.lock().unwrap(); 204 | *lock += 1; 205 | drop(lock); 206 | 207 | do_something_async().await; 208 | } 209 | ``` 210 | 211 | 这是因为当前编译器仅根据作用域范围信息来计算一个future是否为 `Send` . 希望将来对编译器更新后会支持显式的 drop掉它, 但目前而言, 你必须显式 212 | 的使用作用域的方式. 213 | 214 | 注意这里讨论的错误也在 [Send边界](Spawning.md) 里面有讨论. 215 | 216 | 你不应该去尝试,通过不需要一个 `Send` 的方式来产生一个任务来规避这个问题(译者注:也就是一定要使用 `Send`的方式), 是因为当任务持有锁的时候如果Tokio通过 `.await` 暂停任务, 那么可能 217 | 在同一线程上一些其它的任务可能被调度执行, 并且这些其它的任务可能也会尝试锁住互斥锁, 这将导致死锁, 因为等待锁定的互斥锁的任务将阻止持有互斥锁 218 | 的任务释放锁. 219 | 220 | 我们将在下面讨论一些解决错误消息的方法: 221 | 222 | ## 重构代码, 以免在 `.await` 中持有锁(Restructure you code to not hold the lock across an `.await` ) 223 | 我们已经在上面的片段中看到了一个例子, 但这里也有更加强大的方法可能做到这一点. 比如, 你可以包装互斥锁(mutex)到一个结构体(struct)中, 且 224 | 只能将互斥锁在结构体的异步方法中锁定. 225 | 226 | ```rust 227 | use std::sync::Mutex; 228 | 229 | struct CanIncrement { 230 | mutex: Mutex, 231 | } 232 | impl CanIncrement { 233 | // 这个函数没有标识为异步函数 234 | fn increment(&self) { 235 | let mut lock = self.mutex.lock().unwrap(); 236 | *lock += 1; 237 | } 238 | } 239 | 240 | async fn increment_and_do_stuff(can_incr: &CanIncrement) { 241 | can_incr.increment(); 242 | do_something_async().await; 243 | } 244 | ``` 245 | 246 | 这种模式保证你不会遇到 `Send` 类型的错误, 是因为在异步函数的任何地方都不会出现互斥保护. 247 | 248 | ## 产生一个任务来管理状态并使用消息传递机制对其进行操作(Spawn a task to manage the state and use message passing to operate on it) 249 | 这是本章节开头提到了第二种方案, 并且当在 I/O 资源中共享资源时经常使用到. 下一章会展示更多相关的细节. 250 | 251 | ## 使用Tokio的异步互斥锁(Use Tokio's asynchronous mutex) 252 | 也可以使用 Tokio 提供的 `tokio::sync::Mutex` 类型. Tokio互斥锁主要的功能是可以在 `.await` 中持有它, 而不会产生任何问题. 也就是说, 253 | 异步互斥锁比普通互斥锁使用起来更加昂贵, 一般最好是使用其它两种方法中的一种. 254 | 255 | ```rust 256 | use tokio::sync::Mutex; // 注意这里是使用的 tokio的 Mutex 257 | 258 | // 这段代码是能编译的 259 | // (但是这种情况下选择重构代码会更好) 260 | async fn increment_and_do_stuff(mutex: &Mutex) { 261 | let mut lock = mutex.lock().await; 262 | *lock += 1; 263 | 264 | do_something_async().await; 265 | } // lock 在这里超出范围 266 | ``` 267 | 268 | ← [Spawning](Spawning.md) 269 | 270 | → [通道](Channels.md) 271 | -------------------------------------------------------------------------------- /doc/Spawning.md: -------------------------------------------------------------------------------- 1 | ## Spawning 2 | 我们将切换且开始在Redis Server上的工作. 3 | 4 | 首先, 将客户端的 `SET/GET` 代码从上一章节移至一个示例文件中. 这样的话我们可以在服务器上运行它. 5 | 6 | ```shell script 7 | mkdir -p examples 8 | mv src/main.rs examples/hello-redis.rs 9 | ``` 10 | 11 | ## 接收套接字(Accepting sockets) 12 | 我们的Redis服务器需要做的第一件事是接受入站的TCP sockets. 这使用 `tokio::net::TcpListener` 来完成. 13 | 14 | ```text 15 | 大多数Tokio的类型名称被命名为和Rust标准库中具有等效功能的相同类型的名称一样. 在合理的情况个 Tokio 暴露了与 std 库相同的API, 只是tokio使用了 16 | async fn . 17 | ``` 18 | 19 | 一个 `TcpListener` 绑定到端口6379, 然后在loop循接受sockets. 每个socket 都经过处理然后关闭. 现在,我们将读取命令,将它打印到标准输出并返回错误. 20 | 21 | ```rust 22 | use tokio::net::{TcpListener, TcpStream}; 23 | use mini_redis::{Connection, Frame}; 24 | 25 | #[tokio::main] 26 | async fn main() { 27 | // 绑定监听器到一个地址 28 | let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); 29 | 30 | loop { 31 | // 第二项包含新链接的IP与端口 32 | let (socket, _) = listener.accept().await.unwrap(); 33 | process(socket).await; 34 | } 35 | } 36 | 37 | async fn process(socket: TcpStream) { 38 | // "链接" 可以让我们通过字节流 读/写 redis的 **帧**. "链接" 类型被 mini-redis 定义. 39 | let mut connection = Connection::new(socket); 40 | 41 | if let Some(frame) = connection.read_frame().await.unwrap() { 42 | println!("GOT: {:?}", frame); 43 | 44 | // 响应一个错误 45 | let response = Frame::Error("unimplemented".to_string()); 46 | connection.write_frame(&response).await.unwrap(); 47 | } 48 | } 49 | ``` 50 | 51 | 现在运行一个这个accept loop: 52 | 53 | ```shell script 54 | cargo run 55 | ``` 56 | 57 | 在另外一个窗口中,运行 `hello-redis` 示例(上一个章节有 `SET/GET` 命令的示例): 58 | ```shell script 59 | cargo run --example hello-redis 60 | ``` 61 | 62 | 应该会输出: 63 | 64 | ```shell script 65 | Error: "unimplemented" 66 | ``` 67 | 68 | 在服务端终端会输出: 69 | 70 | ```shell script 71 | GOT: Array([Bulk(b"set"), Bulk(b"hello"), Bulk(b"world")]) 72 | ``` 73 | 74 | ## 并发(Concurrency) 75 | 我们的服务有点小问题(除了仅响应错误之外). 它一次处理一个入站请求. 当一个链接被接受后, 服务器将停在accept循环块中直到响应完成写入到socket中为止. 76 | 77 | 我们希望我们的Redis服务能处理 **更多** 的并发请求. 为了做到这一点,我们必须添加一些并发. 78 | 79 | ```text 80 | 并发与并行不是同一件事. 如果你在两个任务之间交替执行, 那么你将同时执行两个任务, 但不能并行执行.(译者注: 这种情况属于并发,不是并行) 81 | 为了使它具有并行性, 你需要两个人, 每个人专门负责每个任务.(译者注: 同时并行的执行,而不是交替). 82 | 83 | 使用tokio的优点是异步代码可以让你同时处理许多并发任务, 而不必使用普通线程并行处理它们. 事实上, Tokio可以在单个线程上并发处理许多任务. 84 | ``` 85 | 86 | 为了同时处理链接,将为每一个入站的新链接产生一个新任务. 这个链接在此任务中处理. 87 | 88 | accept 循环会变为: 89 | ```rust 90 | use tokio::net::TcpListener; 91 | 92 | #[tokio::main] 93 | async fn main() { 94 | let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); 95 | 96 | loop { 97 | let (socket, _) = listener.accept().await.unwrap(); 98 | // 为每一个入站socket链接产生一个新任务. 此socket链接被移动到这个新任务中且在里面处理. 99 | tokio::spawn(async move { 100 | process(socket).await; 101 | }); 102 | } 103 | } 104 | ``` 105 | 106 | ## 任务(Tasks) 107 | 一个Tokio的任务(task)是一个异步的绿色线程. 它们通过 `async` 块 `tokio::spawn` 来创建. `tokio::spawn` 函数返回一个 `JoinHandle` 108 | , 调用者可以使用该 `JoinHandle` 与生成的任务进行交互. `async` 块可以有一个返回值. 调用方可以在 `JoinHandle` 上使用 `.await` 获取返回值. 109 | 110 | 比如: 111 | ```rust 112 | #[tokio::main] 113 | async fn main() { 114 | let handle = tokio::spawn(async { 115 | // 做一些异步的工作 116 | "return value" 117 | }); 118 | 119 | // 作一些其它的工作 120 | 121 | let out = handle.await.unwrap(); 122 | println!("GOT {}", out); 123 | } 124 | ``` 125 | 在 `JoinHandle` 等待返回一个 `Result` . 当任务在处理期间遇到一个错误时, `JoinHandle` 会返回一个 `Err`. 这种情况发生在, 当任务出现 panics 或者 126 | 任务在运行期间被关闭而强制取消时. 127 | 128 | 任务是由调度器管理的执行单元. 产生的任务会提交给Tokio的调度器, 调度器可以确保在有工作要做时执行任务. 产生的任务可以在与产生它的同一线程上执行, 129 | 也可以在不同的运行时线程上执行. 任务产生后也可以在不同的线程之间移动. 130 | 131 | ## 静态边界(`'static bound`) 132 | 通过 `tokio::spawn` 产生的任务必须是 `'static` 的. 产生(Spawned)的表达式不能借用任何数据. 133 | 134 | 有一种普遍的误解是, "静态"意味着"永久存活"("being static" means "lives forever"), 然而情况不并是这样. 如果仅仅因为值是 `'static` 135 | 的话并不意味着存在内存泄露. 有关这点你可以在[Common Rust Lifetime Misconceptions](https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#2-if-t-static-then-t-must-be-valid-for-the-entire-program) 136 | 了解更多. 137 | 138 | 例如, 下面的示例将不能被编译: 139 | ```rust 140 | use tokio::task; 141 | 142 | #[tokio::main] 143 | async fn main() { 144 | let v = vec![1,2,3]; 145 | 146 | task::spawn(async { 147 | println!("Here's a vec: {:?}", v); 148 | }); 149 | } 150 | ``` 151 | 尝试去编译会产生如下错误结果: 152 | ```text 153 | error[E0373]: async block may outlive the current function, but 154 | it borrows `v`, which is owned by the current function 155 | --> src/main.rs:7:23 156 | | 157 | 7 | task::spawn(async { 158 | | _______________________^ 159 | 8 | | println!("Here's a vec: {:?}", v); 160 | | | - `v` is borrowed here 161 | 9 | | }); 162 | | |_____^ may outlive borrowed value `v` 163 | | 164 | note: function requires argument type to outlive `'static` 165 | --> src/main.rs:7:17 166 | | 167 | 7 | task::spawn(async { 168 | | _________________^ 169 | 8 | | println!("Here's a vector: {:?}", v); 170 | 9 | | }); 171 | | |_____^ 172 | help: to force the async block to take ownership of `v` (and any other 173 | referenced variables), use the `move` keyword 174 | | 175 | 7 | task::spawn(async move { 176 | 8 | println!("Here's a vec: {:?}", v); 177 | 9 | }); 178 | | 179 | ``` 180 | 为发生这种情况是因为, 默认情况下, 变量是不能被移动到一个异步块中的. `v` 集合仍然被 `main` 函数所有. `println!` 行借用了 `v` . 181 | rust的编译器能够帮助解释这一点, 甚至可以提出修改的建议! 修改第7行为 `task::spawn(async move {` 这将指示编译器将移动 `v` 到产生的任务中去. 182 | 现在任务拥有它自己的所有数据并使其为 `'static` . 183 | 184 | 如果必须同时从多个并发任务中访问单个数据, 则必须使用共享同步原语, 例如 `Arc` . 185 | 186 | ## Send 边界(`Send` bound) 187 | 通过 `tokio::spawn` 产生的任务必须实现 `Send` . 这允许Tokio运行时在任务使用 `.await` 挂起时可以在不同的线程之间移动他们. 188 | 189 | 当通过 `.await` 调用中保存的所有数据都为 `Send` 时, 任务就是一个 `Send` . 这点有些微妙. 当 `.await` 被调用时任务会返回到调度器. 190 | 下一次任务被执行会从上一次的出让点(point it last yielded)继续.(译者注: 从哪个地方出让并返回到调度器,下一次任务执行时就从那个点恢复). 191 | 若要进行这样的工作, 该任务必须保存 `.await` 之后使用的所有状态. 如果这个状态是 `Send` , 比如, 能在不同线程中移动, 则任务本身就可以跨 192 | 线程移动. 反过来, 如果状态不是 `Send` 的, 那么任务本身也就不能跨线程移动. 193 | 194 | 例如, 这种有效: 195 | ```rust 196 | use tokio::task::yield_now; 197 | use std::rc::Rc; 198 | 199 | #[tokio::main] 200 | async fn main() { 201 | tokio::spawn(async { 202 | // 在 .await 之前作用域强制 rc drop了 203 | { 204 | let rc = Rc::new("hello"); 205 | println!("{}", rc); 206 | } 207 | 208 | // rc 不再使用. 当任务返回到调度器后, rc 不能再持续下去 209 | yield_now().await; 210 | }); 211 | } 212 | ``` 213 | 214 | 这一种情况却不行: 215 | ```rust 216 | use tokio::task::yield_now; 217 | use std::rc::Rc; 218 | 219 | #[tokio::main] 220 | async fn main() { 221 | tokio::spawn(async { 222 | let rc = Rc::new("hello"); 223 | 224 | // rc 在 .await后继续使用, 它必须持久化到 task 的 状态中才行 225 | yield_now().await; 226 | 227 | println!("{}", rc); 228 | }); 229 | } 230 | ``` 231 | 232 | 尝试编译上面的代码片段,会有如下结果: 233 | ```text 234 | error: future cannot be sent between threads safely 235 | --> src/main.rs:6:5 236 | | 237 | 6 | tokio::spawn(async { 238 | | ^^^^^^^^^^^^ future created by async block is not `Send` 239 | | 240 | ::: [..]spawn.rs:127:21 241 | | 242 | 127 | T: Future + Send + 'static, 243 | | ---- required by this bound in 244 | | `tokio::task::spawn::spawn` 245 | | 246 | = help: within `impl std::future::Future`, the trait 247 | | `std::marker::Send` is not implemented for 248 | | `std::rc::Rc<&str>` 249 | note: future is not `Send` as this value is used across an await 250 | --> src/main.rs:10:9 251 | | 252 | 7 | let rc = Rc::new("hello"); 253 | | -- has type `std::rc::Rc<&str>` which is not `Send` 254 | ... 255 | 10 | yield_now().await; 256 | | ^^^^^^^^^^^^^^^^^ await occurs here, with `rc` maybe 257 | | used later 258 | 11 | println!("{}", rc); 259 | 12 | }); 260 | | - `rc` is later dropped here 261 | ``` 262 | 在 [下一章](SharedState.md) 中, 我们将更深入的讨论这种错误的特殊情况. 263 | 264 | ## 存储值(Store values) 265 | 现在我们将实现一个 `process` 函数来处理传入的命令. 我们使用一个 `HashMap` 来存值. `SET` 指令将插入到 `HashMap` 中而 `GET` 指令 266 | 将它们从 `HashMap` 中加载出来. 另外, 我们将使用一个循环来接受每个链接的多个指令. 267 | 268 | ```rust 269 | use tokio::net::TcpStream; 270 | use mini_redis::{Connection, Frame}; 271 | 272 | async fn process(socket: TcpStream) { 273 | use mini_redis::Command::{self, Get, Set}; 274 | use std::collections::HashMap; 275 | 276 | // 存储数据的HashMap 277 | let mut db = HashMap::new(); 278 | 279 | // 通过 mini-redis 提供的链接, 可以处理来自socket中的 帧 280 | let mut connection = Connection::new(socket); 281 | 282 | // 使用 read_frame 来接收一个来自 链接中的 命令 283 | while let Some(frame) = connection.read_frame().await.unwrap() { 284 | let response = match Command::from_frame(frame).unwrap() { 285 | Set(cmd) => { 286 | db.insert(cmd.key().to_string(), cmd.value().clone()); 287 | Frame::Simple("OK".to_string()) 288 | } 289 | Get(cmd) => { 290 | if let Some(value) = db.get(cmd.key()) { 291 | Frame::Bulk(value.clone()) 292 | } else { 293 | Frame::Null 294 | } 295 | } 296 | cmd => panic!("unimplemented {:?}", cmd), 297 | }; 298 | 299 | // 写入响应到客户端 300 | connection.write_frame(&response).await.unwrap(); 301 | } 302 | } 303 | 304 | ``` 305 | 现在启动这个服务: 306 | 307 | ```shell script 308 | cargo run 309 | ``` 310 | 311 | 并且在另外一个窗口中运行 `hello-redis` 示例: 312 | 313 | ```shell script 314 | cargo run --example hello-redis 315 | ``` 316 | 317 | 现在得到了如下的输出: 318 | ```text 319 | got value from the server; success=Some(b"world") 320 | ``` 321 | 322 | 现在我们可以获取和设置一个值, 但是这里还有一个问题: 值不能够在链接中共享. 如果另外一个socket链接尝试通过 `GET` 得到键 `hello` 的值, 323 | 这将不会找任何东西. 324 | 325 | 你可以在 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/spawning/src/main.rs) 找到完整的代码. 326 | 327 | 在下一章节中,我们将为所有的sockets链接实现持久化数据. 328 | 329 | ← [你好Tokio](HelloTokio.md) 330 | 331 | → [共享状态](SharedState.md) 332 | -------------------------------------------------------------------------------- /doc/Streams.md: -------------------------------------------------------------------------------- 1 | ## 流(Streams) 2 | 流是一个一系列异步值的称呼. 它与Rust的 [std::iter::Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) 异步等效且由 3 | [Stream](https://docs.rs/tokio/0.3/tokio/stream/trait.Stream.html) trait表示. 流能在`async`函数中迭代. 它们也可以使用适配器进行 4 | 转换. Tokio在 [StreamExt](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html) trait上提供了一些通用适配器. 5 | 6 | Tokio 在 `stream` 特性标识下提供对流的支持. 当依赖Tokio时, 包括`stream`或`full`的特性能访问此功能. 7 | 8 | ```toml 9 | tokio ={version = "0.3", features = ["stream"]} 10 | ``` 11 | 12 | 我们已经看到了一些类型也实现了[Stream](https://docs.rs/tokio/0.3/tokio/stream/trait.Stream.html). 比如说,[mpsc::Receiver](https://docs.rs/tokio/0.3/tokio/sync/mpsc/struct.Receiver.html) 13 | 的接收(receive)部分也实现了`Stream`. [AsyncBufReadExt::lines()](https://docs.rs/tokio/0.3/tokio/io/trait.AsyncBufReadExt.html#method.lines) 14 | 方法采用一个被缓存的 I/O reader并返回一个 `Stream`,其中每个值代表一行数据. 15 | 16 | ## 迭代(Iteration) 17 | 当前Rust程序语言还不支持异步`for`循环. 取而代之是的使用`while let`循环与 [StreamExt::next()](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html#method.next) 配对来完成流的迭代. 18 | 19 | ```rust 20 | use tokio::stream::StreamExt; 21 | use tokio::sync::mpsc; 22 | 23 | #[tokio::main] 24 | async fn main() { 25 | let (mut tx, mut rx) = mpsc::channel(10); 26 | 27 | tokio::spawn(async move { 28 | tx.send(1).await.unwrap(); 29 | tx.send(2).await.unwrap(); 30 | tx.send(3).await.unwrap(); 31 | }); 32 | 33 | while let Some(v) = rx.next().await { 34 | println!("GOT = {:?}", v); 35 | } 36 | } 37 | ``` 38 | 39 | 像迭代器一样,`next()`方法返回`Option` 其中 `T` 就是流的类型. 接收到 `None` 表明流迭代被终止了. 40 | 41 | ### Mini-Redis 广播(Mini-Redis broadcast) 42 | 让我们来看一个使用Mini-Redis客户端的更加复杂的示例. 43 | 44 | 完整的代码可以看 [这里](https://github.com/tokio-rs/website/blob/master/tutorial-code/streams/src/main.rs). 45 | 46 | ```rust 47 | use tokio::stream::StreamExt; 48 | use mini_redis::client; 49 | 50 | async fn publish() -> mini_redis::Result<()> { 51 | let mut client = client::connect("127.0.0.1:6379").await?; 52 | 53 | // Publish some data 54 | client.publish("numbers", "1".into()).await?; 55 | client.publish("numbers", "two".into()).await?; 56 | client.publish("numbers", "3".into()).await?; 57 | client.publish("numbers", "four".into()).await?; 58 | client.publish("numbers", "five".into()).await?; 59 | client.publish("numbers", "6".into()).await?; 60 | Ok(()) 61 | } 62 | 63 | async fn subscribe() -> mini_redis::Result<()> { 64 | let client = client::connect("127.0.0.1:6379").await?; 65 | let subscriber = client.subscribe(vec!["numbers".to_string()]).await?; 66 | let messages = subscriber.into_stream(); 67 | 68 | tokio::pin!(messages); 69 | 70 | while let Some(msg) = messages.next().await { 71 | println!("got = {:?}", msg); 72 | } 73 | 74 | Ok(()) 75 | } 76 | 77 | #[tokio::main] 78 | async fn main() -> mini_redis::Result<()> { 79 | tokio::spawn(async { 80 | publish().await 81 | }); 82 | 83 | subscribe().await?; 84 | 85 | println!("DONE"); 86 | 87 | Ok(()) 88 | } 89 | ``` 90 | 91 | 产生一个任务来将消息发布到"numbers" 通道上的Mini-Redis服务上. 然后我们在main(主)任务中,订阅"numbers" 通道并显示收到的消息. 92 | 93 | 订阅之后,在返回的订阅者上调用 [into_stream()](https://docs.rs/mini-redis/0.3/mini_redis/client/struct.Subscriber.html#method.into_stream). 94 | 消息者订阅,返回在消息到达时产生消息的流. 在我们开始迭代消息之前,注意到,使用了`tokio::pin!`将流固定到堆栈. 在流上调用`next()`需要流被 95 | [pinned](https://doc.rust-lang.org/std/pin/index.html). `into_stream()` 函数返回的流不是固定的,我们必须显示的固定住它来进行迭代. 96 | 97 | ```markdown 98 | 一个Rust的值是"pinned"时,它会被固定且它不能在内存中移动. 固定值的关键是可以将指针用作固定数据,并且调用都可以确信指针一直保持有效. 99 | `async/await`使用此特性来支持跨`.await`点的数据**借用**. 100 | ``` 101 | 102 | 如果我们忘记固定住流,我们会得到像下面这样的错误: 103 | 104 | ```text 105 | error[E0277]: `std::future::from_generator::GenFuture<[static generator@mini_redis::client::Subscriber::into_stream::{{closure}}#0 0:mini_redis::client::Subscriber, 1:async_stream::yielder::Sender>> for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {std::future::ResumeTy, &'r mut mini_redis::client::Subscriber, mini_redis::client::Subscriber, impl std::future::Future, (), std::result::Result, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't0)>>, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't1)>, &'t2 mut async_stream::yielder::Sender>>, async_stream::yielder::Sender>>, std::result::Result>, impl std::future::Future, std::option::Option, mini_redis::client::Message}]>` cannot be unpinned 106 | --> streams/src/main.rs:22:36 107 | | 108 | 22 | while let Some(msg) = messages.next().await { 109 | | ^^^^ within `impl futures_core::stream::Stream`, the trait `std::marker::Unpin` is not implemented for `std::future::from_generator::GenFuture<[static generator@mini_redis::client::Subscriber::into_stream::{{closure}}#0 0:mini_redis::client::Subscriber, 1:async_stream::yielder::Sender>> for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {std::future::ResumeTy, &'r mut mini_redis::client::Subscriber, mini_redis::client::Subscriber, impl std::future::Future, (), std::result::Result, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't0)>>, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't1)>, &'t2 mut async_stream::yielder::Sender>>, async_stream::yielder::Sender>>, std::result::Result>, impl std::future::Future, std::option::Option, mini_redis::client::Message}]>` 110 | | 111 | ::: /home/carllerche/.cargo/registry/src/github.com-1ecc6299db9ec823/mini-redis-0.2.0/src/client.rs:398:37 112 | | 113 | 398 | pub fn into_stream(mut self) -> impl Stream> { 114 | | ------------------------------------------ within this `impl futures_core::stream::Stream` 115 | | 116 | = note: required because it appears within the type `impl std::future::Future` 117 | = note: required because it appears within the type `async_stream::async_stream::AsyncStream>, impl std::future::Future>` 118 | = note: required because it appears within the type `impl futures_core::stream::Stream` 119 | 120 | error[E0277]: `std::future::from_generator::GenFuture<[static generator@mini_redis::client::Subscriber::into_stream::{{closure}}#0 0:mini_redis::client::Subscriber, 1:async_stream::yielder::Sender>> for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {std::future::ResumeTy, &'r mut mini_redis::client::Subscriber, mini_redis::client::Subscriber, impl std::future::Future, (), std::result::Result, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't0)>>, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't1)>, &'t2 mut async_stream::yielder::Sender>>, async_stream::yielder::Sender>>, std::result::Result>, impl std::future::Future, std::option::Option, mini_redis::client::Message}]>` cannot be unpinned 121 | --> streams/src/main.rs:22:27 122 | | 123 | 22 | while let Some(msg) = messages.next().await { 124 | | ^^^^^^^^^^^^^^^^^^^^^ within `impl futures_core::stream::Stream`, the trait `std::marker::Unpin` is not implemented for `std::future::from_generator::GenFuture<[static generator@mini_redis::client::Subscriber::into_stream::{{closure}}#0 0:mini_redis::client::Subscriber, 1:async_stream::yielder::Sender>> for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {std::future::ResumeTy, &'r mut mini_redis::client::Subscriber, mini_redis::client::Subscriber, impl std::future::Future, (), std::result::Result, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't0)>>, std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync + 't1)>, &'t2 mut async_stream::yielder::Sender>>, async_stream::yielder::Sender>>, std::result::Result>, impl std::future::Future, std::option::Option, mini_redis::client::Message}]>` 125 | | 126 | ::: /home/carllerche/.cargo/registry/src/github.com-1ecc6299db9ec823/mini-redis-0.2.0/src/client.rs:398:37 127 | | 128 | 398 | pub fn into_stream(mut self) -> impl Stream> { 129 | | ------------------------------------------ within this `impl futures_core::stream::Stream` 130 | | 131 | = note: required because it appears within the type `impl std::future::Future` 132 | = note: required because it appears within the type `async_stream::async_stream::AsyncStream>, impl std::future::Future>` 133 | = note: required because it appears within the type `impl futures_core::stream::Stream` 134 | = note: required because of the requirements on the impl of `std::future::Future` for `tokio::stream::next::Next<'_, impl futures_core::stream::Stream>` 135 | 136 | error: aborting due to 2 previous errors 137 | 138 | For more information about this error, try `rustc --explain E0277`. 139 | error: could not compile `streams`. 140 | 141 | To learn more, run the command again with --verbose. 142 | ``` 143 | 144 | 如果你遇到一个像这样的错误,可以尝试将流固定! 145 | 146 | 在运行之前,先启动Mini-Redis 服务: 147 | 148 | ```shell script 149 | $ mini-redis-server 150 | ``` 151 | 152 | 然后尝试运行代码,我们将看到消息在标准输出流中打印. 153 | 154 | ```text 155 | got = Ok(Message { channel: "numbers", content: b"1" }) 156 | got = Ok(Message { channel: "numbers", content: b"two" }) 157 | got = Ok(Message { channel: "numbers", content: b"3" }) 158 | got = Ok(Message { channel: "numbers", content: b"four" }) 159 | got = Ok(Message { channel: "numbers", content: b"five" }) 160 | got = Ok(Message { channel: "numbers", content: b"6" }) 161 | ``` 162 | 163 | 由于订阅与发布之间存在竞争,某些早期的消息可能会被丢弃. 该程序永远不会退出. 只要服务器处于活动状态,对Mini-Redis通道的订阅将保持活动状态. 164 | 165 | 让我们来看看如何使用流来扩展此程序. 166 | 167 | ## 适配器(Adapters) 168 | 接收一个`Stream`并返回一个`Stream`的函数通常被叫做"流适配器"(Stream adapters),因为他们是适配器模式中的一种形式. 公共流适配器包括 169 | [map](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html#method.map),[take](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html#method.take), 170 | 和[filter](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html#method.filter). 171 | 172 | 让我们更新一个Mini-Redis来让它可以退出. 在接收到三个消息之后停止迭代消息. 这可以用`take`. 此适配器限制流最多产生 `n` 个消息. 173 | 174 | ```rust 175 | let message = subscriber.into_stream().take(3); 176 | ``` 177 | 178 | 再次运行程序,我们可以看到: 179 | 180 | ```text 181 | got = Ok(Message { channel: "numbers", content: b"1" }) 182 | got = Ok(Message { channel: "numbers", content: b"two" }) 183 | got = Ok(Message { channel: "numbers", content: b"3" }) 184 | ``` 185 | 186 | 这一次程序可以终止. 187 | 188 | 现在让我们将流限制为一个数字. 我们将通过消息的长度来检查. 我们使用`filter`适配器来删除与条件(译者注: predicate,这里译为条件好点)不匹配的消息. 189 | 190 | ```rust 191 | let messages = subscriber 192 | .into_stream() 193 | .filter(|msg| match msg { 194 | Ok(msg) if msg.content.len() == 1 => true, 195 | _ => false, 196 | }) 197 | .take(3); 198 | ``` 199 | 200 | 再一次执行程序,我们看到: 201 | 202 | ```text 203 | got = Ok(Message { channel: "numbers", content: b"1" }) 204 | got = Ok(Message { channel: "numbers", content: b"3" }) 205 | got = Ok(Message { channel: "numbers", content: b"6" }) 206 | ``` 207 | 208 | 请注意适配器的应用很重要. 首先调用`filter`然后再是`take`与调用`take`再`filter`是不同的. 209 | 210 | 最后我们通过剥离 `Ok(Message { ... }` 的输出部分来整理输出. 这是使用`map`来完成. 因为它应用在`filter`之后,我们知道消息是 `Ok`,所以 211 | 我们可以使用`unwrap()`. 212 | 213 | ```rust 214 | let messages = subscriber 215 | .into_stream() 216 | .filter(|msg| match msg { 217 | Ok(msg) if msg.content.len() == 1 => true, 218 | _ => false, 219 | }) 220 | .map(|msg| msg.unwrap().content) 221 | .take(3); 222 | ``` 223 | 224 | 现在我们得到输出: 225 | 226 | ```text 227 | got = b"1" 228 | got = b"3" 229 | got = b"6" 230 | ``` 231 | 232 | 另外可选的是,组合`filter`与`map`的操作步可以使用 [filter_map](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html#method.filter_map). 233 | 234 | 这里有更多可用的适配器,清单请查看[这里](https://docs.rs/tokio/0.3/tokio/stream/trait.StreamExt.html). 235 | 236 | ## `Stream`的实现(Implementing `Stream`) 237 | [Stream](https://docs.rs/tokio/0.3/tokio/stream/trait.Stream.html) trait与 [Future](https://doc.rust-lang.org/std/future/trait.Future.html) trait非常类似. 238 | 239 | ```rust 240 | use std::pin::Pin; 241 | use std::task::{Context, Poll}; 242 | 243 | pub trait Stream { 244 | type Item; 245 | 246 | fn poll_next( 247 | self: Pin<&mut Self>, 248 | cx: &mut Context<'_> 249 | ) -> Poll>; 250 | 251 | fn size_hint(&self) -> (usize, Option) { 252 | (0, None) 253 | } 254 | } 255 | ``` 256 | 257 | `Stream::poll_next()` 函数与`Future::poll`非常类似,不同之处在于,它可以被重复调来从流中接收多个值. 与我们在[深入异步](AsyncInDepth.md) 258 | 中看到的一样,当流不是就绪状态时将返回`Poll::Pending`. 任务注册waker程序. 一旦应该再次轮询流时,就会通知waker. 259 | 260 | `size_hint()` 方法使用的方式与[iterators](https://doc.rust-lang.org/book/ch13-02-iterators.html)相同. 261 | 262 | 通常当手动实现一个`Stream`时,它是通过组合future和其它流来完成的. 例如,让我们以在[深入异步](AsyncInDepth.md)中实现的`Delay` future为基础. 263 | 我们将它转换成10ms为间隔产生三次`()`的流. 264 | 265 | ```rust 266 | use tokio::stream::Stream; 267 | use std::pin::Pin; 268 | use std::task::{Context, Poll}; 269 | use std::time::Duration; 270 | 271 | struct Interval { 272 | rem: usize, 273 | delay: Delay, 274 | } 275 | 276 | impl Stream for Interval { 277 | type Item = (); 278 | 279 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) 280 | -> Poll> 281 | { 282 | if self.rem == 0 { 283 | // No more delays 284 | return Poll::Ready(None); 285 | } 286 | 287 | match Pin::new(&mut self.delay).poll(cx) { 288 | Poll::Ready(_) => { 289 | let when = self.delay.when + Duration::from_millis(10); 290 | self.delay = Delay { when }; 291 | self.rem -= 1; 292 | Poll::Ready(Some(())) 293 | } 294 | Poll::Pending => Poll::Pending, 295 | } 296 | } 297 | } 298 | ``` 299 | 300 | ### `async-stream` 301 | 使用`Stream` trait手动来实现流可能很繁琐. 不幸的是,Rust语言目前还不支持在流上使用`async/await`语法. 这还在进行中,但现在还没准备好.(译者注: 指在流上的`async/await`语法) 302 | 303 | [async-stream](https://docs.rs/async-stream) 包是一个临时可用的解决方案. 这个包提供了一个`async_stream!`的宏,可以将输入转换成一个流》 304 | 使用这个包,可以像这样实现上面的间隔需求: 305 | 306 | ```rust 307 | use async_stream::stream; 308 | use std::time::{Duration, Instant}; 309 | 310 | stream! { 311 | let mut when = Instant::now(); 312 | for _ in 0..3 { 313 | let delay = Delay { when }; 314 | delay.await; 315 | yield (); 316 | when += Duration::from_millis(10); 317 | } 318 | } 319 | ``` 320 | 321 | ← [Select](Select.md) 322 | 323 | → [词汇表](Glossary.md) 324 | 325 | 326 | -------------------------------------------------------------------------------- /doc/Topics.md: -------------------------------------------------------------------------------- 1 | ### 主题(Topics) 2 | 3 | Tokio的主题页面包含了与编写异步应用时出现的各种主题相关的文章。 4 | 5 | 当前可用的主题文章有: 6 | 7 | * [同步代码桥接 - BridgingWithSyncCode](BridgingWithSyncCode.md) 8 | * [优雅关机 - Graceful shutdown](GracefulShutdown.md) -------------------------------------------------------------------------------- /src/bin/channels-demo.rs: -------------------------------------------------------------------------------- 1 | use bytes::Bytes; 2 | use tokio::sync::{mpsc, oneshot}; 3 | use std::option::Option::Some; 4 | use mini_redis::client; 5 | 6 | /// 由请求者提供并通过管理任务来发送,再将命令的响应返回给请求者. 7 | type Responder = oneshot::Sender>; 8 | 9 | #[derive(Debug)] 10 | enum Command { 11 | Get { 12 | key: String, 13 | resp: Responder>, 14 | }, 15 | Set { 16 | key: String, 17 | val: Vec, 18 | resp: Responder<()>, 19 | }, 20 | } 21 | 22 | 23 | /// 示例配合 store-value 服务端使用, 或者按前面教程里 使用 mini-redis-server 服务端 24 | #[tokio::main] 25 | async fn main() { 26 | let (mut tx, mut rx) = mpsc::channel(32); 27 | 28 | // 产生一个管理任务 29 | let manager = tokio::spawn(async move { 30 | //建立一个与服务器的链接 31 | let mut client = client::connect("127.0.0.1:6379").await.unwrap(); 32 | 33 | // 开始接收redis server 那边的消息 34 | while let Some(message) = rx.recv().await { 35 | use Command::*; 36 | // 匹配redis返回的 命令类型 37 | match message { 38 | Get { key, resp } => { 39 | let res = client.get(&key).await; 40 | let _ = resp.send(res); 41 | } 42 | Set { key, val, resp } => { 43 | let res = client.set(&key, val.into()).await; 44 | let _ = resp.send(res); 45 | } 46 | } 47 | } 48 | }); 49 | 50 | // clone 发送者完成多个任务的发送 51 | let mut tx2 = tx.clone(); 52 | 53 | let t1 = tokio::spawn(async move { 54 | let (resp_tx, resp_rx) = oneshot::channel(); 55 | let cmd = Command::Get { 56 | key: "hello".to_string(), 57 | resp: resp_tx, 58 | }; 59 | // 发送 GET 请求 60 | if tx.send(cmd).await.is_err() { 61 | eprintln!("t1 connection task shutdown"); 62 | return; 63 | } 64 | // 等待响应 65 | let res = resp_rx.await; 66 | println!("T1 GOT = {:?}", res); 67 | }); 68 | 69 | let t2 = tokio::spawn(async move { 70 | let (resp_tx, resp_rx) = oneshot::channel(); 71 | let cmd = Command::Set { 72 | key: "hello".to_string(), 73 | val: "world".into(), 74 | resp: resp_tx, 75 | }; 76 | if tx2.send(cmd).await.is_err() { 77 | eprintln!("t2 connection task shutdown"); 78 | return; 79 | } 80 | // 等待响应 81 | let res = resp_rx.await; 82 | println!("T2 GOT = {:?}", res); 83 | }); 84 | 85 | // while let Some(message) = rx.recv().await { 86 | // println!("Got = {}", message); 87 | // } 88 | 89 | t1.await.unwrap(); 90 | t2.await.unwrap(); 91 | manager.await.unwrap(); 92 | } -------------------------------------------------------------------------------- /src/bin/common/delay.rs: -------------------------------------------------------------------------------- 1 | use std::time::Instant; 2 | use std::future::Future; 3 | use std::pin::Pin; 4 | use std::task::{Poll, Context}; 5 | use std::thread; 6 | 7 | pub struct Delay { 8 | pub when: Instant, 9 | } 10 | 11 | impl Future for Delay { 12 | type Output = &'static str; 13 | 14 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 15 | 16 | if Instant::now() >= self.when { 17 | println!("hello world"); 18 | Poll::Ready("done") 19 | }else { 20 | // 在当前任务上获取一个waker句柄 21 | let waker = cx.waker().clone(); 22 | let when = self.when; 23 | 24 | // 产生一个定时器线程 25 | thread::spawn(move || { 26 | let now = Instant::now(); 27 | 28 | if now < when { 29 | // 说明还没到时间 30 | thread::sleep(when - now); 31 | } 32 | 33 | waker.wake(); 34 | }); 35 | Poll::Pending 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/bin/common/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod delay; -------------------------------------------------------------------------------- /src/bin/echo-client.rs: -------------------------------------------------------------------------------- 1 | use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 2 | use tokio::net::TcpStream; 3 | 4 | #[tokio::main] 5 | async fn main() -> io::Result<()> { 6 | // 链接到一个server 7 | let tcp_stream = TcpStream::connect("127.0.0.1:6124").await?; 8 | 9 | let (mut rd, mut wr) = io::split(tcp_stream); 10 | 11 | let _write_task = tokio::spawn(async move { 12 | wr.write_all(b"hello\r\n").await?; 13 | wr.write_all(b"world\r\n").await?; 14 | 15 | Ok::<_, io::Error>(()) 16 | }); 17 | 18 | 19 | let mut buf = vec![0; 32]; 20 | 21 | // 循环读取从服务端返回的数据 22 | loop { 23 | let n = rd.read(&mut buf).await?; 24 | if n == 0 { 25 | break; 26 | } 27 | println!("GOT message from server {:?}", String::from_utf8(Vec::from(&buf[..n]))); 28 | buf.clear(); 29 | } 30 | 31 | Ok(()) 32 | } -------------------------------------------------------------------------------- /src/bin/echo-server-copy.rs: -------------------------------------------------------------------------------- 1 | use tokio::io; 2 | use tokio::net::TcpListener; 3 | 4 | #[tokio::main] 5 | async fn main() -> io::Result<()> { 6 | let mut listener = TcpListener::bind("127.0.0.1:6124").await.unwrap(); 7 | loop { 8 | let (mut socket,_) = listener.accept().await?; 9 | tokio::spawn(async move{ 10 | let (mut rd, mut wr) = socket.split(); 11 | // 打印一下 12 | // 使用io::copy 直接将reader中的数据复制到writer中去 13 | if io::copy(&mut rd, &mut wr).await.is_err() { 14 | eprintln!("failed to copy"); 15 | } 16 | }); 17 | } 18 | } -------------------------------------------------------------------------------- /src/bin/echo-server.rs: -------------------------------------------------------------------------------- 1 | use tokio::io; 2 | use tokio::net::TcpListener; 3 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; 4 | 5 | #[tokio::main] 6 | async fn main() -> io::Result<()> { 7 | // 绑定一个地址与端口 8 | let mut listener = TcpListener::bind("127.0.0.1:6124").await.unwrap(); 9 | loop { 10 | let (mut socket, _) = listener.accept().await?; 11 | tokio::spawn(async move { 12 | // 缓存buffer 手动复制内容到writer中 13 | let mut buf:Vec =vec![0;32]; 14 | loop { 15 | match socket.read(&mut buf).await { 16 | // 如果是 Ok(0) 表示远程已经关闭链接, 那就直接return 17 | Ok(0) => return, 18 | Ok(n) => { 19 | // 复制数据返回到socket中去, 模式匹配写回并判断是否出错了 20 | println!("Receive data: {:?} from client", String::from_utf8(Vec::from(&buf[..n]))); 21 | if socket.write_all(&buf[..n]).await.is_err() { 22 | // 未期待的错误,不处理直接返回 23 | return; 24 | } 25 | } 26 | Err(_) => return 27 | } 28 | } 29 | }); 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/bin/future-impl-demo.rs: -------------------------------------------------------------------------------- 1 | use tokio::sync::oneshot; 2 | use std::future::Future; 3 | use std::pin::Pin; 4 | use std::task::{Context, Poll}; 5 | 6 | #[tokio::main] 7 | async fn main() { 8 | let (_tx1, rx1) = oneshot::channel(); 9 | let (_tx2, rx2) = oneshot::channel(); 10 | 11 | MySelect { 12 | rx1, 13 | rx2, 14 | }.await 15 | } 16 | 17 | struct MySelect { 18 | rx1: oneshot::Receiver<&'static str>, 19 | rx2: oneshot::Receiver<&'static str>, 20 | } 21 | 22 | 23 | impl Future for MySelect { 24 | type Output = (); 25 | 26 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 27 | if let Poll::Ready(val) = Pin::new(&mut self.rx1).poll(cx) { 28 | println!("rx1 completed first with {:?}", val); 29 | return Poll::Ready(()); 30 | } 31 | 32 | if let Poll::Ready(val) = Pin::new(&mut self.rx2).poll(cx) { 33 | println!("rx2 completed first with {:?}", val); 34 | return Poll::Ready(()); 35 | } 36 | 37 | Poll::Pending 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/bin/hello-redis-server.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::{TcpListener, TcpStream}; 2 | use mini_redis::{Connection, Frame}; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | // 绑定监听器到一个地址 7 | let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); 8 | 9 | // 循环接收 socket 链接 10 | loop { 11 | let (socket, _) = listener.accept().await.unwrap(); 12 | // process(socket).await; 如果直接处理,那么每一次只能处理一个新链接 13 | // 将为每一个入站的新socket链接产生一个新task去处理它 14 | tokio::spawn(async move { 15 | process(socket).await; 16 | }); 17 | } 18 | } 19 | 20 | async fn process(socket: TcpStream) { 21 | let mut connection = Connection::new(socket); 22 | // "链接" 可以让我们通过字节流 读/写 redis的 **帧**. "链接" 类型被 mini-redis 定义. 23 | if let Some(frame) = connection.read_frame().await.unwrap() { 24 | println!("GOT: {:?}", frame); 25 | 26 | // 返回一个错误 27 | let response = Frame::Error("unimplemented".to_string()); 28 | connection.write_frame(&response).await.unwrap(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/bin/hello-tokio.rs: -------------------------------------------------------------------------------- 1 | use mini_redis::{client, Result}; 2 | 3 | #[tokio::main] 4 | pub async fn main() -> Result<()> { 5 | // 打开一个链接到mini-redis地址的链接. 6 | let server_address:&str = "127.0.0.1:6379"; 7 | let mut client = client::connect(server_address).await?; 8 | 9 | // 设置 hello 的值为 world 10 | client.set("hello", "world".into()).await?; 11 | 12 | // 获取 hello 的值 13 | let result = client.get("hello").await?; 14 | 15 | println!("got value from server; result={:?}", result); 16 | 17 | Ok(()) 18 | } -------------------------------------------------------------------------------- /src/bin/io-demo.rs: -------------------------------------------------------------------------------- 1 | use tokio::fs::File; 2 | use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | //read_to_end().await.unwrap(); 7 | //write().await.unwrap(); 8 | //write_to_all().await.unwrap(); 9 | async_copy().await.unwrap(); 10 | } 11 | 12 | /// 异步读read() 13 | #[allow(dead_code)] 14 | async fn read() -> io::Result<()>{ 15 | let mut file = File::open("d:/foo.txt").await?; 16 | // 声明一个buffer 17 | let mut buffer = [0;20]; 18 | 19 | let n = file.read(&mut buffer).await?; 20 | 21 | println!("The bytes : {:?}", n); 22 | println!("The buffer content: {:?}", String::from_utf8(Vec::from(buffer))); 23 | 24 | Ok(()) 25 | } 26 | 27 | /// 异步读取整个文件 28 | #[allow(dead_code)] 29 | async fn read_to_end() -> io::Result<()>{ 30 | let mut f = File::open("d:/foo.txt").await?; 31 | let mut buffer = Vec::new(); 32 | 33 | // 读取整个文件 34 | f.read_to_end(&mut buffer).await?; 35 | 36 | println!("file full content: {:?}", String::from_utf8(buffer)); 37 | 38 | Ok(()) 39 | } 40 | 41 | /// 读取文件中的所有内容到一个buffer中去 42 | #[allow(dead_code)] 43 | async fn read_to_all(buffer: &mut Vec) { 44 | let mut f = File::open("d:/foo.txt").await.unwrap(); 45 | f.read_to_end(buffer).await.unwrap(); 46 | } 47 | 48 | #[allow(dead_code)] 49 | async fn write() -> io::Result<()> { 50 | let mut file = File::create("d:/create.txt").await?; 51 | 52 | // 写入一些字符串 53 | let n = file.write(b"some chars").await?; 54 | println!("write the first {} bytes of 'some bytes", n); 55 | 56 | Ok(()) 57 | } 58 | 59 | #[allow(dead_code)] 60 | async fn write_to_all() -> io::Result<()> { 61 | let mut file = File::create("d:/create1.txt").await?; 62 | 63 | // 从foo.txt文件中读取内容并写入到create1.txt中去 64 | let mut buffer:Vec = Vec::new(); 65 | read_to_all(&mut buffer).await; 66 | //再将buffer中的数据写到新文件中去 67 | file.write_all(buffer.as_slice()).await?; 68 | Ok(()) 69 | } 70 | 71 | 72 | #[allow(dead_code)] 73 | async fn async_copy() -> io::Result<()> { 74 | // 实现将foo.txt reader中的内容不通过buffer直接copy到writer中去 75 | let mut target_file = File::create("d:/foo_copy.txt").await?; // 创建目标文件, 它也就是一个writer 76 | // 源文件 77 | let mut src_file = File::open("d:/foo.txt").await?; 78 | // tokio::io::copy 可以异步的将reader中的内容copy到writer中去 79 | io::copy(&mut src_file, &mut target_file).await?; 80 | 81 | Ok(()) 82 | } 83 | -------------------------------------------------------------------------------- /src/bin/mini-tokio-one.rs: -------------------------------------------------------------------------------- 1 | use std::collections::VecDeque; 2 | use std::future::Future; 3 | use std::pin::Pin; 4 | use std::task::Context; 5 | use futures::task; 6 | use std::option::Option::Some; 7 | use std::time::{Instant, Duration}; 8 | 9 | mod common; 10 | 11 | use common::delay::Delay; 12 | 13 | /// mini-tokio 第一版 14 | fn main() { 15 | let mut mini_tokio = MiniTokio::new(); 16 | 17 | mini_tokio.spawn(async { 18 | let when = Instant::now() + Duration::from_millis(10); 19 | let future = Delay { when }; 20 | 21 | let out = future.await; 22 | 23 | println!("out result: {}", out); 24 | }); 25 | 26 | mini_tokio.run(); // 如果没执行这一句,将不会有任何的结果 27 | } 28 | 29 | struct MiniTokio { 30 | tasks: VecDeque, 31 | } 32 | 33 | type Task = Pin + Send>>; 34 | 35 | 36 | impl MiniTokio { 37 | // 初始化一个MiniTokio 对象 38 | fn new() -> Self { 39 | MiniTokio { tasks: VecDeque::new() } 40 | } 41 | 42 | // 在mini-tokio实例上产生一个future 43 | fn spawn(&mut self, future: F) 44 | where 45 | F: Future + Send + 'static, 46 | { 47 | self.tasks.push_back(Box::pin(future)); 48 | } 49 | 50 | fn run(&mut self) { 51 | // 创建一个新waker 52 | let waker = task::noop_waker(); 53 | let mut context = Context::from_waker(&waker); 54 | 55 | // 循环队列中拿任务task 并匹配, 56 | while let Some(mut task) = self.tasks.pop_front() { 57 | if task.as_mut().poll(&mut context).is_pending() { 58 | self.tasks.push_back(task); 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/bin/mini-tokio-two.rs: -------------------------------------------------------------------------------- 1 | use crossbeam::channel; 2 | use std::sync::{Arc, Mutex}; 3 | use std::pin::Pin; 4 | use futures::{task, task::ArcWake, Future}; 5 | use std::task::{Context}; 6 | use std::time::{Instant, Duration}; 7 | 8 | mod common; 9 | use common::delay::Delay; 10 | 11 | fn main() { 12 | let mut mini_tokio = MiniTokio::new(); 13 | mini_tokio.spawn(async { 14 | println!("这一句先打印出来!"); 15 | let when = Instant::now() + Duration::from_millis(10); 16 | let future = Delay { when }; 17 | 18 | let out = future.await; 19 | 20 | println!("out result: {}", out); 21 | }); 22 | mini_tokio.run(); 23 | } 24 | 25 | 26 | struct Task { 27 | future: Mutex + Send>>>, 28 | executor: channel::Sender>, 29 | } 30 | 31 | impl Task { 32 | fn schedule(self: &Arc) { 33 | let _ = self.executor.send(self.clone()); 34 | } 35 | 36 | fn poll(self: Arc) { 37 | // 从task实例上创建一个waker. 它使用 ArcWake 38 | let waker = task::waker(self.clone()); 39 | let mut context = Context::from_waker(&waker); 40 | // 没有其它线程试图锁住 future,所以可以try_lock() 41 | let mut future = self.future.try_lock().unwrap(); 42 | 43 | // 轮询future 44 | let _ = future.as_mut().poll(&mut context); 45 | } 46 | 47 | /// 使用指定的future产生一个新的任务 48 | /// 49 | /// 初始化一个新的task,它包含了future,完成后将task 推送到队列中, channel的另外一半receiver将接收到它们. 50 | fn spawn(future: F, sender: &channel::Sender>) 51 | where F: Future + Send + 'static, 52 | { 53 | let task = Arc::new(Task { 54 | future: Mutex::new(Box::pin(future)), 55 | executor: sender.clone(), 56 | }); 57 | 58 | let _ = sender.send(task); 59 | } 60 | } 61 | 62 | impl ArcWake for Task { 63 | fn wake_by_ref(arc_self: &Arc) { 64 | arc_self.schedule(); 65 | } 66 | } 67 | 68 | struct MiniTokio { 69 | scheduled: channel::Receiver>, 70 | sender: channel::Sender>, 71 | } 72 | 73 | impl MiniTokio { 74 | 75 | // 此run方法,将会一直执行 76 | fn run(&self) { 77 | while let Ok(task) = self.scheduled.recv() { 78 | task.poll(); 79 | } 80 | } 81 | 82 | fn new() -> Self { 83 | let (sender, scheduled) = channel::bounded(100); 84 | MiniTokio { sender, scheduled } 85 | } 86 | 87 | /// MiniTokio 产生一个future 88 | fn spawn(&mut self, future: F) 89 | where F: Future + Send + 'static 90 | { 91 | Task::spawn(future, &self.sender) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/bin/mini-tokio.rs: -------------------------------------------------------------------------------- 1 | //! 演示了如何实现一个非常基础的异步Rust执行器与计时器. 2 | use std::pin::Pin; 3 | use std::time::{Instant, Duration}; 4 | use std::future::Future; 5 | use std::task::{Context, Poll, Waker}; 6 | use std::option::Option::Some; 7 | use std::result::Result::Ok; 8 | use std::sync::{Arc, Mutex}; 9 | use std::cell::RefCell; 10 | use std::thread; 11 | // 使用一个channel队列来调度tasks, 之所以不用std中的channel是因为std中的channel不是 Sync的,无法在线程中共享 12 | use crossbeam::channel; 13 | // 允许我们不使用 “不安全” 的代码来实现一个 `sta::task::waker` 功能的 工具 14 | use futures::task::{ArcWake, self}; 15 | 16 | // 用于跟踪当前的mini-tokio实例,来使 spawn 函数能调度产生的实例. 17 | thread_local! { 18 | static CURRENT: RefCell>>> = RefCell::new(None); 19 | } 20 | 21 | /// main 函数入口,创建一个mini-tokio实例,并产生一些任务(Task). 我们的mini-tokio实现仅支持产生task和设置delays 22 | /// 23 | /// 此MiniTokio,源于官方指南中的MiniTokio 原理代码,原代码链接 [mini-tokio](https://github.com/tokio-rs/website/blob/master/tutorial-code/mini-tokio/src/main.rs) 24 | fn main() { 25 | // 创建一个新MiniTokio实例 26 | let mut mini_tokio = MiniTokio::new(); 27 | 28 | // 产生一个root 根据任务,所有其它的tasks都来自于这个上下文. 直到mini_tokio.run()调用之前,不会执行任何工作. 29 | mini_tokio.spawn(async { 30 | // 产生一个任务 31 | spawn(async { 32 | // 等待一小段时间以便 world在 hello后面打印 33 | delay(Duration::from_secs(5)).await; 34 | println!("world") 35 | }); 36 | 37 | // 产生第二个任务 38 | spawn(async { 39 | println!("hello"); 40 | }); 41 | 42 | //我们没有实现执行器的shutdown功能,因此这里强制关闭 43 | delay(Duration::from_secs(10)).await; // 2秒后关闭吧 44 | std::process::exit(0); 45 | }); 46 | 47 | 48 | // 启动mini-tokio 执行器循环,调度任务并接收执行结果 49 | mini_tokio.run(); 50 | } 51 | 52 | /// 此spawn函数功能与tokio::spawn()一样. 当进行到mini-tokio执行器(executor)中时, 53 | /// 'CURRENT' 本地线程(thread-local) 被设置指向执行器 channel的 Send 方. 然后,产生task需要为创建的"Task"套上 54 | /// 一个"future" 并将其推到调度队列里面. 55 | pub fn spawn(future: F) 56 | where F: Future + Send + 'static, 57 | { 58 | CURRENT.with(|cell| { 59 | let borrow = cell.borrow(); 60 | let sender = borrow.as_ref().unwrap(); 61 | Task::spawn(future, sender); 62 | }); 63 | } 64 | 65 | /// task 包含一个future和一旦future被唤醒后所必须要的数据 66 | struct Task { 67 | // future使用 Mutex 来包装可以使用Task具有Sync 特性. 68 | // 仅有一个线程可以使用future. 69 | // 真实tokio运行时,没有使用Mutex这种排它锁,而是使用了unsafe代码. box也被避免使用了. 70 | future: Mutex + Send>>>, 71 | // 当task被通知时,它被发送到队列中去. 执行器通过取出通知任务来执行它们 72 | executor: channel::Sender>, 73 | } 74 | 75 | impl Task { 76 | // 使用指定的future产生一个新的future 77 | // 初始化一个新的包含了指定future的task,并将其它推送给 sender. channel另外一半的receiver将接收到它并执行. 78 | fn spawn(future: F, sender: &channel::Sender>) 79 | where F: Future + Send + 'static, 80 | { 81 | let task = Arc::new(Task { 82 | future: Mutex::new(Box::pin(future)), 83 | executor: sender.clone(), 84 | }); 85 | let _ = sender.send(task); 86 | } 87 | 88 | // 执行调度任务. 它创建了必须的 `task::Context`上下文,此Context,包含了一个waker与task. 89 | // 使用waker对future进行poll. 90 | fn poll(self: Arc) { 91 | // 从task实例上创建一个waker, 它使用了 ArcWake 92 | let waker = task::waker(self.clone()); 93 | // 使用waker来初始化task的上下文 94 | let mut cx = Context::from_waker(&waker); 95 | 96 | // 这里绝不会阻塞,因为只有一个线程能锁住future 97 | let mut future = self.future.try_lock().unwrap(); 98 | 99 | // 轮询future 100 | let _ = future.as_mut().poll(&mut cx); 101 | } 102 | } 103 | 104 | // 在标准库中使用了一个低级别的API来定义waker,此API是unsafe的,为了不写unsafe代码,这里我们使用futures包提供的 105 | // ArcWake 来定义一个waker,它可以被 Task结构体来调度. 106 | impl ArcWake for Task { 107 | fn wake_by_ref(arc_self: &Arc) { 108 | // 调度Task来执行.执行器从channel中接收Task并poll Task. 109 | let _ = arc_self.executor.send(arc_self.clone()); 110 | } 111 | } 112 | 113 | 114 | /// 一个基于channel的非常基础的futures 执行器(executor). 当任务(task)被唤醒时,它们通过在channel的发送方 115 | /// 中来排队调度. 执行器在接收方(receiver)等待并执行接收到的任务. 116 | /// 117 | /// 当一个任务被执行时,channel的发送方(sender)传递任务的Waker. 118 | struct MiniTokio { 119 | // 接收调度的任务. 当一个任务被安排(或调度)时, 与之相关的future会准备好推进. 这通常发生在资源任务准备执行操作的时候 120 | // 比如说 一个socket接收到数据且一个 read 将调用成功时. 121 | scheduled: channel::Receiver>, 122 | sender: channel::Sender>, 123 | } 124 | 125 | 126 | impl MiniTokio { 127 | // 初始化一个新的mini-tokio实例 128 | fn new() -> MiniTokio { 129 | let (sender, scheduled) = channel::bounded(1000); 130 | MiniTokio{scheduled, sender} 131 | } 132 | 133 | // 在mini-tokio实例上产生一个future 134 | // 给future 包装task 并将其推送到 scheduled 队列中去,当run方法被调用时future将会执行 135 | fn spawn(&mut self, future: F) 136 | where F:Future + Send + 'static, 137 | { 138 | Task::spawn(future, &self.sender) 139 | } 140 | 141 | /// 运行执行器 142 | /// 143 | /// 这将启动执行器循环,并无限的运行,没有实现关机的机制 144 | /// 145 | /// 任务从 scheduled 通道的 receiver方出来. 在channel上接收一个任务表明任务已经准备好被执行了. 146 | /// 这发生在任务首次被创建和任务被唤醒时. 147 | fn run(&self) { 148 | println!("execute MiniTokio run method!"); 149 | 150 | // 设置 CURRENT 线程局部变量来指向当前执行器 151 | // tokio 使用一个thread local变量来实现 `tokio::spawn`. 152 | CURRENT.with(|cell|{ 153 | *cell.borrow_mut() = Some(self.sender.clone()); 154 | }); 155 | 156 | while let Ok(task) = self.scheduled.recv() { 157 | task.poll(); 158 | } 159 | } 160 | } 161 | 162 | 163 | // 异步等待,其作用相当于 thread::sleep. 尝试在当前函数上暂停指定的时间 164 | // 165 | // mini-tokio 通过一个计时器线程(timer thread) 来实现Delay, sleep 指定的duration后,一旦delay完成,就会 166 | // 通知调用者. 每次调用delay都会产生一个线程. 显然这不是一个好的实施策略,没有人会将这种方法用在生产上(这里只是为了示例tokio原理) 167 | // 真实的tokio没有使用这种策略. 168 | async fn delay(dur: Duration) { 169 | 170 | // delay 在这里是一种片面的future描述. 有时候,它被当作一种 "resource"(资源). 其它的资源包括,socket与channels. 171 | // resource 可能不是按 async/await 来实现的,因为它们必须与一些操作系统细节合并. 因为这一原因,我们必须手动来实现 future 172 | // 173 | // 不过,最好将API公共为一个 async fn . 一个有用的方式是,手动定义私有future,然后从公共(pub)的`async fn`中使用它的API. 174 | 175 | struct Delay { 176 | // delay什么时候完成 177 | when: Instant, 178 | // 一旦delay完成后就会通知waker. waker必须能被timer线程与future访问,所以它使用Arc>来包装. 179 | waker: Option>>, 180 | } 181 | 182 | // 为Delay 实现 Future trait 183 | impl Future for Delay { 184 | type Output = (); 185 | 186 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 187 | // 首先,如果第一次future就被调用,则产生一个timer线程. 如果timer线程已经在运行了,要确保存储的waker 188 | // 能匹配上当前task的waker. 189 | // 看是否能匹配上当前task的waker 190 | if let Some(waker) = &self.waker { 191 | let mut waker = waker.lock().unwrap(); 192 | 193 | if !waker.will_wake(cx.waker()) { 194 | *waker = cx.waker().clone(); 195 | } 196 | }else { 197 | // 如果不能匹配上,创建一个waker 198 | let when = self.when; 199 | let waker = Arc::new(Mutex::new(cx.waker().clone())); 200 | // 赋值给当前task的waker 201 | self.waker = Some(waker.clone()); 202 | 203 | // 每一次poll 被调用,产生一个timer线程 204 | thread::spawn(move ||{ 205 | let now = Instant::now(); 206 | // 如果还没到时间 207 | if now < when { 208 | // 睡眠一下剩余的时间 209 | thread::sleep(when - now); 210 | } 211 | // 如果duration时间过去后,再通过激活waker来通知调用者 212 | let waker = waker.lock().unwrap(); 213 | waker.wake_by_ref(); 214 | }); 215 | } 216 | 217 | // 一旦waker被存储且timer线程已经开始时,此时就要来检查delay是否已经完成了. 这通过当前时间来检查. 218 | // 如果duration时间已过,Future就完成了,此时返回Poll::Ready() 219 | if Instant::now() >= self.when { 220 | // 说明delay duration时间已经过去 221 | Poll::Ready(()) // 返回Poll::Ready() 222 | }else { 223 | // 时间没过返回Poll::Pending 224 | Poll::Pending 225 | } 226 | } 227 | } 228 | 229 | // 回到delay function中, 初始化一个Delay实全 230 | let future = Delay { 231 | when: Instant::now() + dur, 232 | waker: None, // 初始时并没有waker,它由poll去创建 233 | }; 234 | 235 | // 等待duration完成 236 | future.await; 237 | } 238 | -------------------------------------------------------------------------------- /src/bin/my-future.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | use std::time::{Instant, Duration}; 3 | use common::delay::Delay; 4 | 5 | #[tokio::main] 6 | async fn main() { 7 | // when = 现在的时间戳+ 10ms 8 | let when = Instant::now() + Duration::from_millis(10); 9 | // 初始化一个Delay 10 | let future = Delay{when}; 11 | 12 | println!("Before future.await call"); 13 | 14 | let out = future.await; 15 | 16 | println!("future.await result : {}", out) 17 | } 18 | -------------------------------------------------------------------------------- /src/bin/not-compile.rs: -------------------------------------------------------------------------------- 1 | use tokio::task; 2 | 3 | #[tokio::main] 4 | async fn main() { 5 | let v = vec![1,2,4]; 6 | 7 | task::spawn(async move { 8 | println!("Here's a vec: {:?}", v); 9 | }); 10 | } -------------------------------------------------------------------------------- /src/bin/select-borrow.rs: -------------------------------------------------------------------------------- 1 | use tokio::sync::oneshot; 2 | 3 | #[tokio::main] 4 | async fn main() -> std::io::Result<()> { 5 | let (tx1, rx1) = oneshot::channel(); 6 | let (tx2, rx2) = oneshot::channel(); 7 | 8 | let mut out = String::new(); 9 | 10 | tokio::spawn(async move { 11 | let _ = tx1.send("hello"); 12 | }); 13 | tokio::spawn(async move { 14 | let _ = tx2.send("world"); 15 | }); 16 | 17 | tokio::select! { 18 | Ok(str) = rx1 => { 19 | out.push_str(format!("rx1 completed: {}", str).as_str()); 20 | } 21 | 22 | Ok(str) = rx2 => { 23 | out.push_str(format!("rx2 completed: {}", str).as_str()); 24 | } 25 | } 26 | println!("{}", out); 27 | Ok(()) 28 | } -------------------------------------------------------------------------------- /src/bin/select-demo.rs: -------------------------------------------------------------------------------- 1 | use tokio::sync::oneshot; 2 | 3 | #[tokio::main] 4 | async fn main() { 5 | let (tx1, rx1) = oneshot::channel(); 6 | let (tx2, rx2) = oneshot::channel(); 7 | 8 | tokio::spawn(async { 9 | let _ = tx1.send("one"); 10 | }); 11 | 12 | tokio::spawn(async { 13 | let _ = tx2.send("two"); 14 | }); 15 | 16 | // 谁先完成返回谁,其它的丢弃 17 | tokio::select! { 18 | va1 = rx1 => { 19 | println!("rx1 completed first with {:?}", va1); 20 | } 21 | 22 | va1 = rx2 => { 23 | println!("rx2 completed first with {:?}", va1); 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /src/bin/select-syntax-demo.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::TcpStream; 2 | use tokio::sync::oneshot; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | let (sender, receiver) = oneshot::channel(); 7 | 8 | // 生产一个任务来发送消息到 oneshot中去 9 | tokio::spawn(async move { 10 | sender.send("one").unwrap(); 11 | }); 12 | 13 | tokio::select! { 14 | // 这里不会被匹配上 15 | socket = TcpStream::connect("localhost:3465") => { 16 | println!("Socket connected {:?}", socket); 17 | } 18 | 19 | msg = receiver => { 20 | println!("receiver message first: {:?}", msg); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/bin/send-bound.rs: -------------------------------------------------------------------------------- 1 | use tokio::task::yield_now; 2 | use std::rc::Rc; 3 | use std::sync::Arc; 4 | 5 | #[tokio::main] 6 | async fn main() { 7 | tokio::spawn(async { 8 | // 通过 {} 作用域 使用 rc 在 .await前drop掉 9 | { 10 | let rc = Rc::new("hello"); 11 | println!("{}", rc); 12 | } 13 | 14 | // rc 没有被使用了,所以当task返回到调度器时, 它不需要持续下去 15 | // 所以这个例子没问题 16 | yield_now().await; // 出让线程返回tokio 运行时调度器 17 | }); 18 | 19 | // 但是如果改为下面这种就不能被编译 20 | tokio::spawn(async { 21 | let rc = Rc::new("hello"); 22 | // 如果改为Arc就没有问题,因为 Arc 实现了 Send + Sync + 'static 23 | //let rc = Arc::new("hello"); 24 | 25 | yield_now().await; 26 | 27 | // rc 在 .await之后还在使用, 它必须被保存在 task 的 状态中,这里没有保存所以不行 28 | println!("{}", rc); 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /src/bin/shared-state.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::{TcpListener, TcpStream}; 2 | use std::collections::HashMap; 3 | use std::sync::{Arc, Mutex}; 4 | use bytes::Bytes; 5 | use mini_redis::{Connection, Frame, Command}; 6 | use std::option::Option::Some; 7 | use mini_redis::cmd::Command::{Set, Get}; 8 | 9 | type Db = Arc>>; 10 | 11 | #[tokio::main] 12 | async fn main() -> std::io::Result<()>{ 13 | // 声明一个listener 并绑定到指定地址的一个端口上 14 | let mut listener = TcpListener::bind("127.0.0.1:6379").await?; 15 | println!("Listening localhost and port 6379"); 16 | 17 | let db = Arc::new(Mutex::new(HashMap::new())); 18 | 19 | loop { 20 | let (socket, _) = listener.accept().await?; 21 | // clone 22 | let db = db.clone(); 23 | println!("Accepted"); 24 | // 处理socket 25 | process(socket, db).await; 26 | } 27 | 28 | } 29 | 30 | /// 处理函数 31 | async fn process(socket: TcpStream, db: Db) { 32 | let mut connection = Connection::new(socket); 33 | 34 | while let Some(frame) = connection.read_frame().await.unwrap() { 35 | let response = match Command::from_frame(frame).unwrap() { 36 | Set(cmd) => { 37 | let mut db = db.lock().unwrap(); 38 | db.insert(cmd.key().to_string(), cmd.value().clone()); 39 | // 返回 frame 40 | Frame::Simple("OK".to_string()) 41 | } 42 | Get(cmd) => { 43 | let db = db.lock().unwrap(); 44 | if let Some(value) = db.get(cmd.key()) { 45 | Frame::Bulk(value.clone()) 46 | }else { 47 | Frame::Null 48 | } 49 | } 50 | // 其它cmd 情况 51 | cmd=> panic!("unimplemented Command :{:?}", cmd), 52 | }; 53 | connection.write_frame(&response).await.unwrap(); 54 | } 55 | } -------------------------------------------------------------------------------- /src/bin/store-value.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::{TcpStream, TcpListener}; 2 | use mini_redis::{Connection, Frame}; 3 | 4 | async fn process(socket: TcpStream) { 5 | use mini_redis::Command::{self, Get, Set}; 6 | use std::collections::HashMap; 7 | 8 | // 声明一个用来存储数据的hashmap 9 | let mut db = HashMap::new(); 10 | 11 | // 此connection 由mini_redis包提供, 可以处理socket中的 帧 12 | let mut connection = Connection::new(socket); 13 | 14 | while let Some(frame) = connection.read_frame().await.unwrap() { 15 | let response = match Command::from_frame(frame).unwrap() { 16 | Set(cmd) => { 17 | db.insert(cmd.key().to_string(), cmd.value().clone()); 18 | Frame::Simple("OK".to_string()) 19 | } 20 | Get(cmd) => { 21 | if let Some(value) = db.get(cmd.key()) { 22 | // Frame::Bulk() 里面要是一个Bytes 使用 into() 转换为 Bytes 23 | Frame::Bulk(value.clone().into()) 24 | }else { 25 | Frame::Null 26 | } 27 | } 28 | // 其它的命令没有实现 29 | cmd=> panic!("unimplemented {:?}", cmd), 30 | }; 31 | // 写入响应到客户端 32 | connection.write_frame(&response).await.unwrap(); 33 | } 34 | } 35 | 36 | #[tokio::main] 37 | async fn main() { 38 | // 绑定监听器到一个地址 39 | let mut listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); 40 | println!("Mini Redis Server started, listen port: {}", 6379); 41 | loop { 42 | let (socket, _) = listener.accept().await.unwrap(); 43 | tokio::spawn(async move { 44 | process(socket).await; 45 | }); 46 | } 47 | } -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod tools; 2 | mod relational; 3 | 4 | fn main() { 5 | println!("Welcome Tokio CN doc and demo!"); 6 | } -------------------------------------------------------------------------------- /src/relational/connection.rs: -------------------------------------------------------------------------------- 1 | use tokio::net::TcpStream; 2 | use mini_redis::{Frame, Result}; 3 | use bytes::BytesMut; 4 | use tokio::io::AsyncReadExt; 5 | 6 | pub struct Connection { 7 | stream: TcpStream, 8 | buffer: BytesMut, 9 | } 10 | 11 | impl Connection { 12 | pub fn new(stream: TcpStream) -> Connection { 13 | Connection { 14 | stream, 15 | // 默认分配4kb容量给buffer 16 | buffer: BytesMut::with_capacity(4 * 1024), 17 | } 18 | } 19 | /// 从链接中读取一个帧,如果EOF到就返回 None 20 | pub async fn read_frame(&mut self) -> Result>{ 21 | loop { 22 | // 尝试从缓冲区中解析一个帧,如果buffer中有足够的数据那么帧就返回 23 | if let Some(frame) = self.parse_frame()? { 24 | return Ok(Some(frame)); 25 | } 26 | 27 | // 如果没有足够的数据读取到一个帧中,那么尝试从socket中读取更多的数据 28 | // 如果成功了,一定数量的字节被返回, 0 表时到了流的末尾了. 29 | if 0 == self.stream.read_buf(&mut self.buffer).await? { 30 | // 远程关闭了链接, 为了彻底关闭,读缓冲区中应该没有数据了,如果还存在数据那说明对等方在发送帧时关闭了socket 31 | return if self.buffer.is_empty() { 32 | Ok(None) 33 | }else { 34 | Err("connection reset by peer".into()) 35 | } 36 | } 37 | 38 | } 39 | } 40 | 41 | /// 写一个帧到链接中 42 | pub async fn write_frame(&mut self, frame:&Frame) -> Result<()> { 43 | 44 | } 45 | 46 | fn parse_frame() -> Result<()>{ 47 | 48 | } 49 | } -------------------------------------------------------------------------------- /src/relational/frame_enum.rs: -------------------------------------------------------------------------------- 1 | use bytes::Bytes; 2 | 3 | enum Frame { 4 | Simple(String), 5 | Error(String), 6 | Integer(u64), 7 | Bulk(Bytes), 8 | Null, 9 | Array(Vec), 10 | } -------------------------------------------------------------------------------- /src/relational/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod connection; 2 | pub mod frame_enum; -------------------------------------------------------------------------------- /src/tools/mod.rs: -------------------------------------------------------------------------------- 1 | mod tools; 2 | 3 | -------------------------------------------------------------------------------- /src/tools/tools.rs: -------------------------------------------------------------------------------- 1 | use rand::{SeedableRng, StdRng, Rng}; 2 | 3 | 4 | /// 根据一个种子值获取原data中的随机num个元素,data.len() 必须 > num 5 | /// 6 | /// seed: u32 类型的种子, data: vec数组, num: 要随机的元素个数 7 | /// 8 | /// 返回一个新的vec 9 | pub fn get_random_by_seed(seed: u32, data: &Vec, num: usize) -> Box> { 10 | let data_len = data.len(); 11 | if data_len < num { 12 | panic!("num 必须小于 data集合元素的个数"); 13 | } 14 | let mut seed_rng = StdRng::seed_from_u64(seed as u64); 15 | // index_ck 用来检查已经出现的索引值 16 | let mut index_ck: Vec = Vec::new(); 17 | let size = data.len(); 18 | // 存放新的集合 19 | let mut new_list: Vec = Vec::new(); 20 | while index_ck.len() < num { 21 | let temp: f32 = seed_rng.gen(); 22 | // 取到目标索引值 23 | let v: u32 = (temp * size as f32) as u32; 24 | // 如果查找vec,不存在v值则添加进new_list中 25 | if !index_ck.binary_search(&v).is_ok() { 26 | // index_ck 中 插入一个值 27 | index_ck.push(v); 28 | match data.get(v as usize) { 29 | Some(result) => { 30 | new_list.push(*result); 31 | } 32 | None => panic!("没有对应的索引") 33 | }; 34 | } 35 | } 36 | Box::from(new_list) 37 | } 38 | 39 | #[test] 40 | fn test_random() { 41 | let seed: u32 = 20180521; 42 | let ori_data: Vec = vec![100001, 100002, 100003, 100004, 100005, 100006, 100007]; 43 | let num = 3; 44 | 45 | // 测试从一个vec中根据种子随机获取4个值 46 | let random_by_seed = get_random_by_seed(seed, &ori_data, num); 47 | println!("result box: {:?}", random_by_seed); 48 | } --------------------------------------------------------------------------------