Simple example with spawn and join
authorGreg Burri <greg.burri@gmail.com>
Tue, 18 Apr 2023 13:36:25 +0000 (15:36 +0200)
committerGreg Burri <greg.burri@gmail.com>
Tue, 18 Apr 2023 13:36:25 +0000 (15:36 +0200)
.gitignore [new file with mode: 0644]
Cargo.lock [new file with mode: 0644]
Cargo.toml [new file with mode: 0644]
src/main.rs [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..ea8c4bf
--- /dev/null
@@ -0,0 +1 @@
+/target
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644 (file)
index 0000000..ead8c1c
--- /dev/null
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "concurrent"
+version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644 (file)
index 0000000..6d8c0f2
--- /dev/null
@@ -0,0 +1,8 @@
+[package]
+name = "concurrent"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
diff --git a/src/main.rs b/src/main.rs
new file mode 100644 (file)
index 0000000..22a0f50
--- /dev/null
@@ -0,0 +1,28 @@
+use std::thread;
+
+fn main() {
+    spawn_and_join();
+}
+
+// Page 500.
+fn spawn_and_join() {
+    let mut handles = Vec::<thread::JoinHandle<_>>::new();
+    for i in 0..10 {
+        let h =
+            thread::spawn(move || {
+                if i == 5 {
+                    panic!("ERROR"); // Simulate an error.
+                }
+                println!("\nHello from thread {}", i);
+                i + 1
+            });
+        handles.push(h);
+    }
+
+    for h in handles {
+        match h.join() {
+            Ok(r) => println!("\nResult: {}", r),
+            Err(err) => println!("\nError: {:?}", err)
+        }
+    }
+}
\ No newline at end of file