Skip to content
Rust

Concurrent Programming

Threads and channels.

By EZ4Code Team
concurrencyconcurrency

Code

use std::thread;
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;

fn main() {
    // Create thread
    let handle = thread::spawn(|| {
        for i in 1..5 {
            println!("Child thread: {}", i);
            thread::sleep(Duration::from_millis(10));
        }
    });

    for i in 1..3 {
        println!("Main thread: {}", i);
        thread::sleep(Duration::from_millis(10));
    }
    handle.join().unwrap();

    // Channel communication
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let msgs = vec!["hi", "from", "thread"];
        for msg in msgs {
            tx.send(msg).unwrap();
        }
    });
    for received in rx {
        println!("Received: {}", received);
    }

    // Shared state
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        }));
    }
    for h in handles { h.join().unwrap(); }
    println!("Count: {}", *counter.lock().unwrap());
}

Explanation

thread::spawn creates threads; mpsc channels pass messages; Arc<Mutex<T>> implements safe sharing.

More Rust Snippets