Rust in Action Notes Chapter 10 Processes, Threads, and Containers

  1. Rust's closure is similar to a lambda expression. The general format is that the parameters |a, b| {...}in the vertical line are the parameters, and the function logic in the curly braces;
  2. 通过thread::spawn(|| {})产生的线程,括号内的参数实际上就是一个闭包,因为创建新的线程不需要参数,因此就是两个竖线跟着一个花括号里面要做的事;如果闭包里面要用到外面的变量,就必须在前面加上move关键字,把外面的变量“捕获”(capture)到闭包内部,为什么要move到闭包内部,因为闭包的逻辑由新产生的线程来完成,他可能比外面的线程活得久(outlive),而Rust总是要求访问的数据是有效的,因此要把外部的变量的所有权移动(move)到闭包内部,如果不想使用move,可以有两个方案,一个是为需要move的变量实现Copy特征,另一个是把要移动的变量设置为Static
  3. When multiple threads are spawned and the handle is put into one Vec<thread::JoinHandle<()>>, if you want to join all the handles, the book does not recommend using for loop, but while let Some(handle) = handlers.pop() {}because the for loop does not allow modification of the traversed variables, but while can, (in fact, the for loop can also be modified now);
  4. The closure is actually an anonymous struct, which implements std::ops::FnOncethe feature, and may implement std::ops::Fnor std::ops::FnMut; the function (function) is actually a function pointer (function pointer), and the function pointer points to the code (code) instead of the data (data). In this scenario, the code (code) is marked as executable (executable). In some complex cases, the closure without capturing parameters is also a function pointer;
  5. The most commonly used method of multi-threaded access to the same variable is Arc<Mutex<T>>to wrap the data to be accessed T; the other is to Channelscreate a sender Senderand receiver Receiver;
  6. ChannelIt is one-way transmission. If two-way transmission (duplex) is required, the suggestion in the book is to create two Channels, each channel corresponds to one direction, and the channel can be used to implement a task queue (task queue). See Page358 for details;
  7. 任务的规模和并发度是有一个取舍的,在10.5节的图中有一个简单的阐述,最左边的Green Thread可以理解为是协程Figure 10.58. 10.5节分别从小到大讲了几个计算机处理任务的单元,从线程、进程、WebAssembly、容器(container)、操作系统,值得注意的是,WASM比进程更大一级,在web这个运行时里,每一个WASM模块里的程序都是隔离的(体现在内存隔离、任务不相干扰),这一点跟进程类似,但WASM又运行在浏览器上,进程是在操作系统上,这一点可以看出WASM处于进程和操作系统之间;容器(Containers)有点类似K8s中的pod概念,进程共享一个文件系统(file system),而Containers自带文件系统;

Guess you like

Origin blog.csdn.net/Mint2yx4/article/details/131518784