R

Concurrency

Rust syntax guide

Writing safe and efficient concurrent code in Rust

Concurrency

Writing safe and efficient concurrent code in Rust

Rust concurrency (rust)
        
          use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::sync::mpsc;

// Basic thread creation
fn basic_threads() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    handle.join().unwrap();

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

// Moving data into threads
fn move_data() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}

// Message passing with channels
fn message_passing() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
        // println!("val is {}", val); // Error: val was moved
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

// Multiple producers
fn multiple_producers() {
    let (tx, rx) = mpsc::channel();
    let tx2 = tx.clone();

    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_millis(100));
        }
    });

    thread::spawn(move || {
        let vals = vec![
            String::from("more"),
            String::from("messages"),
            String::from("for"),
            String::from("you"),
        ];

        for val in vals {
            tx2.send(val).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}

// Shared state with Mutex
fn shared_state() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

// Read-write lock
use std::sync::RwLock;

fn read_write_lock() {
    let lock = Arc::new(RwLock::new(5));
    let lock_clone = Arc::clone(&lock);

    let handle = thread::spawn(move || {
        let read_guard = lock_clone.read().unwrap();
        println!("Read value: {}", *read_guard);
        // Multiple readers can hold the lock simultaneously
    });

    {
        let write_guard = lock.write().unwrap();
        *write_guard += 1;
        println!("Modified value to: {}", *write_guard);
    } // Write lock is released here

    handle.join().unwrap();
}

// Async programming (experimental in stable Rust)
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// Simple async function
async fn hello_world() {
    println!("Hello, world!");
}

// Async function with await
async fn async_example() -> String {
    hello_world().await; // Wait for hello_world to complete
    String::from("Done!")
}

fn main() {
    // Basic threads
    println!("=== Basic Threads ===");
    basic_threads();

    // Move data
    println!("\n=== Move Data ===");
    move_data();

    // Message passing
    println!("\n=== Message Passing ===");
    message_passing();

    // Multiple producers
    println!("\n=== Multiple Producers ===");
    multiple_producers();

    // Shared state
    println!("\n=== Shared State ===");
    shared_state();

    // Read-write lock
    println!("\n=== Read-Write Lock ===");
    read_write_lock();

    // Note: Async example requires async runtime like tokio
    // println!("\n=== Async Example ===");
    // let future = async_example();
    // This would need an async runtime to execute
}
        
      

Explanation

Rust provides powerful concurrency primitives like threads and channels (for message passing) that are designed to be safe and prevent common concurrency bugs at compile time, thanks to its ownership and borrowing system.

Common Use Cases

  • Parallelizing computations
  • Building responsive user interfaces
  • Developing high-performance servers
  • Handling background tasks

Related Rust Syntax

Master Concurrency in Rust

Understanding concurrency is fundamental to writing clean and efficient Rust code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using concurrency effectively in your Rust projects.

Key Takeaways

  • Parallelizing computations
  • Building responsive user interfaces
  • Developing high-performance servers