From: Martin Pitt Date: Sun, 29 Aug 2021 07:21:30 +0000 (+0200) Subject: concepts: Threads and message passing X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=cf171920f1d9768f922556b13042e3a3465483f3 concepts: Threads and message passing --- diff --git a/concepts/src/main.rs b/concepts/src/main.rs index 06d122b..65fb785 100644 --- a/concepts/src/main.rs +++ b/concepts/src/main.rs @@ -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(); }