rust学习材料为官网的《The Rust Programming Language》。本笔记包括第16-17章的内容~
Chapter 16 Fearless Concurrency
本章主要内容有:
- 如何创建多线程
- Message-passing concurrency
- Shared-state concurrency
Sync
和Send
trait
16.1 Using Threads to Run Code Simultaneously
在你的程序中的不同的,同时进行的进程称为thread。由于threads的运行顺序无法保证,会带来很多问题,例如:
- Race Conditions,线程以不同的顺序访问数据或资源
- Deadlocks,死锁
- Bugs
rust采用1:1的threading
Creating a New Thread with spawn
调用thread::spawn函数,向其传递一个闭包,闭包中包含新thread的代码。
注意当main中的线程结束时,spawn中的会强制结束,无论是否运行完毕。