-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy paththread.rs
More file actions
61 lines (50 loc) · 1.31 KB
/
thread.rs
File metadata and controls
61 lines (50 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![allow(unused)]
use std::thread;
use std::thread::JoinHandle;
use std::time::Duration;
fn main() {
let t1: JoinHandle<()> = thread::spawn(|| {
for i in 0..5 {
println!("t1: {i}");
thread::sleep(Duration::from_millis(10));
}
});
let t2: JoinHandle<()> = thread::spawn(|| {
for i in 0..5 {
println!("t2: {i}");
thread::sleep(Duration::from_millis(10));
}
});
// Waits until handle terminates
t1.join().unwrap();
t2.join().unwrap();
// Return value from thread
let t: JoinHandle<u32> = thread::spawn(|| {
return 1;
});
let v = t.join().unwrap();
println!("value: {v}");
// move
let v = vec![1, 2, 3];
// Closure may outlive the main function so transfer ownership of v
let t = thread::spawn(move || {
println!("{v:?}");
});
// Cannot compile - ownership transferred into closure above
// println!("{:?}", v);
t.join().unwrap();
// Panic
let t = thread::spawn(|| {
panic!("💀");
});
// This will crash the main thread
// t.join().unwrap();
match t.join() {
Ok(v) => {
println!("Thread ok: {:?}", v);
}
Err(err) => {
println!("Thread error: {:?}", err);
}
}
}