📅  最后修改于: 2020-11-02 04:24:32             🧑  作者: Mango
在并发编程中,程序的不同部分独立执行。另一方面,在并行编程中,程序的不同部分同时执行。随着越来越多的计算机利用其多个处理器,这两个模型同样重要。
我们可以使用线程同时运行代码。在当前的操作系统中,已执行程序的代码在一个进程中运行,并且操作系统一次管理多个进程。在您的程序中,您还可以具有可以同时运行的独立部分。运行这些独立部分的功能称为线程。
thread :: spawn函数用于创建新线程。生成函数将闭包作为参数。闭包定义应由线程执行的代码。以下示例从主线程打印一些文本,从新线程打印其他文本。
//import the necessary modules
use std::thread;
use std::time::Duration;
fn main() {
//create a new thread
thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
//code executed by the main thread
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 4 from the main thread!
主线程打印从1到4的值。
注意-当主线程结束时,新线程将停止。每次该程序的输出可能会有所不同。
thread :: sleep函数强制线程在短时间内停止执行,从而允许其他线程运行。线程可能会轮流使用,但不能保证–这取决于操作系统如何调度线程。在此运行中,即使从代码生成的线程中首先出现打印语句,也将首先打印主线程。此外,即使将生成的线程编程为将值打印到9,也只能在关闭主线程之前将值打印到5。
产生的线程可能无法运行或完全运行。这是因为主线程快速完成。函数spawn
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 2 from the main thread!
hi number 3 from the spawned thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
主线程和衍生线程继续切换。
注–由于调用join()方法,主线程等待生成的线程完成。