-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathscoped_thread.rs
More file actions
62 lines (45 loc) · 1.24 KB
/
Copy pathscoped_thread.rs
File metadata and controls
62 lines (45 loc) · 1.24 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
62
#![allow(unused)]
use std::thread;
// Scoped thread
// - borrow
// - threads are automatically joined
fn main() {
// Normal threads cannot borrow
let msg = "hello".to_string();
// Must move ownership of msg into thread
thread::spawn(move || {
println!("thread: {:?}", msg);
});
// This doesn't compile - ownership of msg transferred to thread above
// println!("main thread: {:?}", msg);
// Scoped threads can borrow
let msg = "hello".to_string();
thread::scope(|scope| {
println!("scored thread: {:?}", msg);
});
println!("main thread: {:?}", msg);
// Auto join
let t1 = thread::spawn(|| {
println!("thread 1");
});
let t2 = thread::spawn(|| {
println!("thread 2");
});
t1.join().unwrap();
t2.join().unwrap();
thread::scope(|scope| {
scope.spawn(|| {
println!("scoped thread 1");
});
scope.spawn(|| {
println!("scoped thread 2");
});
});
// Return values from scoped thread
let (v1, v2) = thread::scope(|scope| {
let t1 = scope.spawn(|| 1);
let t2 = scope.spawn(|| 2);
(t1.join().unwrap(), t2.join().unwrap())
});
println!("{} {}", v1, v2);
}