Skip to content

Commit 5b2675e

Browse files
committed
channels
1 parent 9300db3 commit 5b2675e

File tree

4 files changed

+42
-4
lines changed

4 files changed

+42
-4
lines changed

course/src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use basics;
22
use myutils::stuff;
33
use myutils::testing;
44
//use guessgame
5+
use paral::channels;
56
use paral::threads;
67

78
fn main() {
@@ -16,4 +17,5 @@ fn main() {
1617
intmut::intmut();
1718
intmut::weakrefs();
1819
threads::demo();
20+
channels::demo();
1921
}

paral/src/channels.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use std::{sync::mpsc, thread};
2+
3+
pub fn demo() {
4+
println!("Channels");
5+
let (tx, rx) = mpsc::channel();
6+
let tx2 = tx.clone();
7+
8+
thread::spawn(move || {
9+
let vals = vec![
10+
String::from("hi"),
11+
String::from("from"),
12+
String::from("the"),
13+
String::from("thread"),
14+
];
15+
for val in vals {
16+
tx.send(val).unwrap();
17+
thread::sleep(std::time::Duration::from_secs(1));
18+
}
19+
});
20+
21+
thread::spawn(move || {
22+
let vals = vec![
23+
String::from("more"),
24+
String::from("messages"),
25+
String::from("for"),
26+
String::from("you"),
27+
];
28+
for val in vals {
29+
tx2.send(val).unwrap();
30+
thread::sleep(std::time::Duration::from_secs(1));
31+
}
32+
});
33+
34+
for received in rx {
35+
println!("Got: {}", received);
36+
}
37+
}

paral/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
pub mod channels;
12
pub mod threads;

paral/src/threads.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::{thread, time::Duration};
33
pub fn demo() {
44
println!("Threads");
55
let handle = thread::spawn(|| {
6-
for i in 1..10 {
6+
for i in 1..5 {
77
println!("hi number {} from the spawned thread!", i);
88
thread::sleep(Duration::from_millis(1));
99
}
@@ -13,9 +13,7 @@ pub fn demo() {
1313

1414
let v = vec![1, 2, 3];
1515
let handle = thread::spawn(move || {
16-
for i in 1..10 {
17-
println!("{}: Here's a vector: {:?}", i, v);
18-
}
16+
println!("Here's a vector: {:?}", v);
1917
});
2018
handle.join().unwrap();
2119
}

0 commit comments

Comments
 (0)