Multiple threads can run concurrently within the same program and can be spawned at any time.
一个程序中的多个线程可以并行执行,可以使用spawn创建新的线程.
When the main thread ends, the entire program ends.
当主线程运行结束,程序也就退出了。无论其它线程是否还在执行。
Data races are undefined behavior, which is fully prevented (in safe code) by Rust’s type system.
数据竞争(多线程竞争)会使程序结果不确定。Rust通过类型系统竭力阻止代码中出现数据竞争。
Data that is Send can be sent to other threads, and data that is Sync can be shared between threads
数据如果是Send的就可以发送到其它线程中,如果数据是Sync的就可以在线程间共享。
Regular threads might run as long as the program does, and thus can only borrow 'static data such as statics and leaked allocations
普通的线程有可能跟程序运行一样长的时间,所以需要借用有静态生命周期('static)的数据或者使用泄露分配(Box::leak)
Reference counting ( Arc ) can be used to share ownership to make sure data lives as long as at least one thread is using it
可以使用引用计数Arc确保数据存活的时间跟使用它的线程一样长
Scoped threads are useful to limit the lifetime of a thread to alllow it to borrow non- 'static data, such as local variables.
可以使用有范围的线程限制线程的生命周期,这样就可以借用非静态生命周期的数据了。
&T is a shared reference. &mut T is an exclusive reference. Regular types do not allow mutation through a shared reference.
&T是共享引用,&mut T是排它引用。普通的类型是不支持通过共享引用实现可变操作的。
Some types have interior mutability, thanks to UnsafeCell , which allows for mutation through shared references.
有些类型具备内部可变性,通过它可以实现使用共享引用修改数据,这要感谢UnsafeCell。
Cell and RefCell are the standard types for single-threaded interior mutability. Atomics, Mutex , and RwLock are their multi threaded equivalents.
Cell和RefCell是在单线程中提供内部可变能力的标准类型. 在多线程环境中要用Atomics,Mutex或RwLock。
Cell and atomics only allow replacing the value as a whole, while RefCell , Mutex , and RwLock allow you to mutate the value directly by dynamically enforcing access rules
Cell和Automics只支持完整的替换值,而RefCell, Mutex, 和RwLock可以借助动态强制访问规则修改值。
Thread parking can be a convenient way to wait for some condition
当线程需要等待触发条件时可以考虑使用线程thread::park();
When a condition is about data protected by a Mutex , using a Condvar is more convenient, and can be more efficient, than thread parking
当条件取决于已经被Mutex保护的数据时,使用Condvar会更方便也相对使用thread::park更高效。