Skip to content

Commit

Permalink
Update 4.多线程.md
Browse files Browse the repository at this point in the history
  • Loading branch information
fyhhub authored Nov 12, 2023
1 parent fc07385 commit 449fc16
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/rust-learn/4.多线程.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,34 @@ fn main() {

调用 `handle.join().unwrap()`, 可以等待handle对应的子线程结束后执行。

## 三、使用move转移线程外的所有权
如果不使用`move`关键字,有可能存在子线程还没执行完,主线程已经结束的情况,这种情况下`arr`的生命周期无法保证能活到子线程结束,所以需要move来转移所有权到子线程中
```rust
fn main() {
let arr = [1;10];
let handle = thread::spawn(move || { // [!code ++]
for item in 0..10 {
println!("子线程: {}", arr[item]);
thread::sleep(Duration::from_millis(100))
};
});


handle.join().unwrap();

for item in 0..10 {
println!("主线程: {}", item);

// 延迟一毫秒,如果不延迟,可能子线程还没执行,主线程就结束了
thread::sleep(Duration::from_millis(1));
};

println!("主线程结束");
}
```

调用 `handle.join().unwrap()`, 可以等待handle对应的子线程结束后执行。

## 三、创建线程的性能

**创建一个线程大概需要 0.24 毫秒,随着线程的变多,这个值会变得更大**
Expand Down Expand Up @@ -83,4 +111,4 @@ fn main() {
handle.join().unwrap();
}
}
```
```

0 comments on commit 449fc16

Please sign in to comment.