Skip to content

Commit bde94de

Browse files
committed
Add thread example
1 parent 5625a84 commit bde94de

File tree

2 files changed

+81
-11
lines changed

2 files changed

+81
-11
lines changed

documentation2/B09-Thread.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# [Thread](https://www.programiz.com/rust/thread)
2+
3+
A thread is the smallest executable unit of a process.
4+
5+
Threads allow us to split the computation in our program into multiple threads. Running multiple tasks at the same time can improve performance of the code. However, it can add complexity.
6+
7+
____
8+
9+
## Creating a New Thread in Rust
10+
11+
In Rust, we can create a native operating system thread using the `thread::spawn()` function from the `std` module. The spawn method takes a closure as an argument.
12+
13+
Here is the syntax of `thread::spawn()`,
14+
15+
```rust
16+
thread::spawn(|| {
17+
// code to execute in the thread
18+
})
19+
```
20+
21+
Now, let's see an example.
22+
23+
```rust
24+
use std::thread;
25+
use std::time::Duration;
26+
27+
fn main() {
28+
// create a thread
29+
thread::spawn(|| {
30+
// everything in here runs in a separate thread
31+
for i in 0..10 {
32+
println!("{} from the spawned thread!", i);
33+
thread::sleep(Duration::from_millis(2));
34+
}
35+
});
36+
37+
// main thread
38+
for i in 0..5 {
39+
println!("{} from the main thread!", i);
40+
thread::sleep(Duration::from_millis(1));
41+
}
42+
}
43+
```
44+
45+
```bash
46+
cargo build
47+
```
48+
49+
```bash
50+
cargo run
51+
```
52+
53+
### Output
54+
55+
```bash
56+
0 from the main thread!
57+
0 from the spawned thread!
58+
1 from the main thread!
59+
1 from the spawned thread!
60+
2 from the main thread!
61+
3 from the main thread!
62+
2 from the spawned thread!
63+
4 from the main thread!
64+
3 from the spawned thread!
65+
```
Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
// A macro which uses repetitions
2-
macro_rules! repeat_print {
3-
// match rule which matches multiple expressions in an argument
4-
($($x:expr),*) => {
5-
$(
6-
println!("{}", $x);
7-
)*
8-
};
9-
}
1+
use std::thread;
2+
use std::time::Duration;
103

114
fn main() {
12-
// Call the macro with multiple arguments
13-
repeat_print!(1, 2, 3);
5+
// create a thread
6+
thread::spawn(|| {
7+
// everything in here runs in a separate thread
8+
for i in 0..10 {
9+
println!("{} from the spawned thread!", i);
10+
thread::sleep(Duration::from_millis(2));
11+
}
12+
});
13+
14+
// main thread
15+
for i in 0..5 {
16+
println!("{} from the main thread!", i);
17+
thread::sleep(Duration::from_millis(1));
18+
}
1419
}

0 commit comments

Comments
 (0)