]> piware.de Git - learn-rust.git/commitdiff
concepts: Threads and message passing
authorMartin Pitt <martin@piware.de>
Sun, 29 Aug 2021 07:21:30 +0000 (09:21 +0200)
committerMartin Pitt <martin@piware.de>
Sun, 29 Aug 2021 07:21:30 +0000 (09:21 +0200)
concepts/src/main.rs

index 06d122b9c4c727f399d8273312ffcfb2a95088fd..65fb785c838a2a966e6c1d4c5494f4751d5f0b0d 100644 (file)
@@ -4,6 +4,7 @@ mod lib;
 use std::collections::HashMap;
 use std::io::{prelude::*, ErrorKind};
 use std::fs::{self, File};
+use std::{thread, time, sync};
 
 use lib::*;
 use word_utils::{first_word, second_word};
@@ -189,6 +190,46 @@ fn test_iterators() {
     }
 }
 
+fn test_threads() {
+    let t1 = thread::spawn(|| {
+        for i in 0..10 {
+            println!("hello #{} from thread", i);
+            thread::sleep(time::Duration::from_millis(1));
+        }
+    });
+
+    for i in 1..5 {
+        println!("hello #{} from main", i);
+        thread::sleep(time::Duration::from_millis(1));
+    }
+
+    t1.join().unwrap();
+
+    let (tx1, rx) = sync::mpsc::channel();
+    let tx2 = tx1.clone();
+
+    let sender1 = thread::spawn(move || {
+        for s in ["hey", "from", "sender", "one"] {
+            tx1.send(s).expect("failed to send");
+            thread::sleep(time::Duration::from_millis(100));
+        }
+    });
+
+    let sender2 = thread::spawn(move || {
+        for s in ["Servus", "von", "Produzent", "zwei"] {
+            tx2.send(s).expect("failed to send");
+            thread::sleep(time::Duration::from_millis(100));
+        }
+    });
+
+    for received in rx {
+        println!("received {} from mpsc", received);
+    }
+
+    sender1.join().unwrap();
+    sender2.join().unwrap();
+}
+
 fn main() {
     test_strings();
     test_vectors();
@@ -197,4 +238,5 @@ fn main() {
     test_generics();
     test_closures();
     test_iterators();
+    test_threads();
 }