summaryrefslogtreecommitdiffstats
path: root/src/threads
diff options
context:
space:
mode:
authorhybrid <hybrid@hybridlabs.cc>2026-10-31 03:54:43 +0300
committerhybrid <hybrid@hybridlabs.cc>2026-10-31 03:54:43 +0300
commit62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2 (patch)
treeb8461eda6cce3f9bbfb2261dd828077e17c7d226 /src/threads
parent18ad654357d6cca34782aaa269f5e8e06cbe9241 (diff)
downloadrust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.tar.gz
rust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.tar.bz2
rust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.zip
add: 7 craits
smartpointers interior_mutability threads mutex hello-async async_concurrency multi_futures
Diffstat (limited to '')
-rw-r--r--src/threads/Cargo.toml6
-rw-r--r--src/threads/src/main.rs93
2 files changed, 99 insertions, 0 deletions
diff --git a/src/threads/Cargo.toml b/src/threads/Cargo.toml
new file mode 100644
index 0000000..f210198
--- /dev/null
+++ b/src/threads/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "threads"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
diff --git a/src/threads/src/main.rs b/src/threads/src/main.rs
new file mode 100644
index 0000000..18b2645
--- /dev/null
+++ b/src/threads/src/main.rs
@@ -0,0 +1,93 @@
+use std::thread;
+use std::time::Duration;
+
+use std::sync::mpsc;
+
+fn main() {
+ let handle = thread::spawn(|| {
+ for i in 1..10 {
+ println!("hi number {i} from the spawned thread!");
+ thread::sleep(Duration::from_millis(1));
+ }
+ });
+
+ for i in 1..5 {
+ println!("hi number {i} from the main thread!");
+ thread::sleep(Duration::from_millis(1));
+ }
+
+ handle.join().unwrap();
+
+ let v = vec![1, 2, 3];
+
+ let handle_vec = thread::spawn(move || {
+ println!("Here's a vector: {v:?}");
+ });
+
+ handle_vec.join().unwrap();
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let val = String::from("hi");
+ tx.send(val).unwrap();
+ });
+
+ let received = rx.recv().unwrap();
+ println!("Got: {received}");
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let vals = vec![
+ String::from("hi"),
+ String::from("from"),
+ String::from("the"),
+ String::from("thread"),
+ ];
+
+ for val in vals {
+ tx.send(val).unwrap();
+ thread::sleep(Duration::from_secs(1));
+ }
+ });
+
+ for received in rx {
+ println!("Got: {received}");
+ }
+
+ let (tx, rx) = mpsc::channel();
+
+ let tx1 = tx.clone();
+ thread::spawn(move || {
+ let vals = vec![
+ String::from("hi"),
+ String::from("from"),
+ String::from("the"),
+ String::from("thread"),
+ ];
+
+ for val in vals {
+ tx1.send(val).unwrap();
+ thread::sleep(Duration::from_secs(1));
+ }
+ });
+
+ thread::spawn(move || {
+ let vals = vec![
+ String::from("more"),
+ String::from("messages"),
+ String::from("for"),
+ String::from("you"),
+ ];
+
+ for val in vals {
+ tx.send(val).unwrap();
+ thread::sleep(Duration::from_secs(1));
+ }
+ });
+
+ for received in rx {
+ println!("Got: {received}");
+ }
+}