-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.rs
More file actions
48 lines (43 loc) · 1.08 KB
/
Copy paththread.rs
File metadata and controls
48 lines (43 loc) · 1.08 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
// Copyright 2024 GOTHAM Inc. All Rights Reserved.
// Author: easytojoin@163.com (jok)
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
fn first_thread() {
let handler = thread::spawn(|| {
println!("Hello world!");
"Success"
});
let result = handler.join().unwrap();
println!("{}", result);
}
fn counter() {
let counter = Arc::new(Mutex::new(0));
let handlers: Vec<_> = (0..10)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
})
})
.collect();
for handler in handlers {
handler.join().unwrap();
}
println!("Counter: {}", *counter.lock().unwrap());
}
fn communication() {
let (sender, receiver) = mpsc::channel();
thread::spawn(move || {
sender.send(format!("Sender from {}", 1)).unwrap();
});
let message = receiver.recv().unwrap();
println!("Received: {}", message);
}
fn main() {
first_thread();
counter();
communication();
}