Rust Concurrent Programming

2026-01-19T00:00:00

Rust Concurrent Programming Example

This snippet demonstrates concurrent programming in Rust using threads and channels.

RUST

1
2    use std::sync::{Arc, Mutex};
3    use std::thread;
4    use std::time::Duration;
5    use std::sync::mpsc;
6    
7    fn main() {
8        println!("=== Rust Concurrent Programming Example ===\n");
9        
10        // Example 1: Basic thread spawning
11        basic_thread_example();
12        
13        // Example 2: Shared state with Arc<Mutex<>>
14        shared_state_example();
15        
16        // Example 3: Channel communication
17        channel_example();
18    }
19    
20    fn basic_thread_example() {
21        println!("1. Basic Thread Example:");
22        
23        let handles: Vec<_> = (0..5)
24            .map(|i| {
25                thread::spawn(move || {
26                    println!("Thread {} started", i);
27                    thread::sleep(Duration::from_millis(100 * i));
28                    println!("Thread {} finished", i);
29                    i * 2
30                })
31            })
32            .collect();
33        
34        for handle in handles {
35            let result = handle.join().unwrap();
36            println!("Thread result: {}", result);
37        }
38        println!();
39    }
40    
41    fn shared_state_example() {
42        println!("2. Shared State Example:");
43        
44        let counter = Arc::new(Mutex::new(0));
45        let mut handles = vec![];
46        
47        for _ in 0..10 {
48            let counter_clone = Arc::clone(&counter);
49            let handle = thread::spawn(move || {
50                let mut num = counter_clone.lock().unwrap();
51                *num += 1;
52            });
53            handles.push(handle);
54        }
55        
56        for handle in handles {
57            handle.join().unwrap();
58        }
59        
60        println!("Result: {}", *counter.lock().unwrap());
61        println!();
62    }
63    
64    fn channel_example() {
65        println!("3. Channel Communication Example:");
66        
67        let (tx, rx) = mpsc::channel();
68        
69        thread::spawn(move || {
70            let vals = vec![
71                String::from("hi"),
72                String::from("from"),
73                String::from("the"),
74                String::from("thread"),
75            ];
76            
77            for val in vals {
78                tx.send(val).unwrap();
79                thread::sleep(Duration::from_millis(100));
80            }
81        });
82        
83        for received in rx {
84            println!("Got: {}", received);
85        }
86        println!();
87    }
    

Rust Concurrent Programming

Rust Concurrent Programming Example

This snippet demonstrates concurrent programming in Rust using threads and channels.

RUST

1
2    use std::sync::{Arc, Mutex};
3    use std::thread;
4    use std::time::Duration;
5    use std::sync::mpsc;
6    
7    fn main() {
8        println!("=== Rust Concurrent Programming Example ===\n");
9        
10        // Example 1: Basic thread spawning
11        basic_thread_example();
12        
13        // Example 2: Shared state with Arc<Mutex<>>
14        shared_state_example();
15        
16        // Example 3: Channel communication
17        channel_example();
18    }
19    
20    fn basic_thread_example() {
21        println!("1. Basic Thread Example:");
22        
23        let handles: Vec<_> = (0..5)
24            .map(|i| {
25                thread::spawn(move || {
26                    println!("Thread {} started", i);
27                    thread::sleep(Duration::from_millis(100 * i));
28                    println!("Thread {} finished", i);
29                    i * 2
30                })
31            })
32            .collect();
33        
34        for handle in handles {
35            let result = handle.join().unwrap();
36            println!("Thread result: {}", result);
37        }
38        println!();
39    }
40    
41    fn shared_state_example() {
42        println!("2. Shared State Example:");
43        
44        let counter = Arc::new(Mutex::new(0));
45        let mut handles = vec![];
46        
47        for _ in 0..10 {
48            let counter_clone = Arc::clone(&counter);
49            let handle = thread::spawn(move || {
50                let mut num = counter_clone.lock().unwrap();
51                *num += 1;
52            });
53            handles.push(handle);
54        }
55        
56        for handle in handles {
57            handle.join().unwrap();
58        }
59        
60        println!("Result: {}", *counter.lock().unwrap());
61        println!();
62    }
63    
64    fn channel_example() {
65        println!("3. Channel Communication Example:");
66        
67        let (tx, rx) = mpsc::channel();
68        
69        thread::spawn(move || {
70            let vals = vec![
71                String::from("hi"),
72                String::from("from"),
73                String::from("the"),
74                String::from("thread"),
75            ];
76            
77            for val in vals {
78                tx.send(val).unwrap();
79                thread::sleep(Duration::from_millis(100));
80            }
81        });
82        
83        for received in rx {
84            println!("Got: {}", received);
85        }
86        println!();
87    }