Day 13i: Multithreading and Vectors – Sharing Data Across Threads

Venkat Annangi
Venkat Annangi
08/10/2024 02:36 2 min read 55 views
#rust-vectors #rust #108 days of rust

Day 13i: Multithreading and Vectors – Sharing Data Across Threads

Introduction

In Rust, multithreading can be a powerful tool, but it comes with challenges, especially when sharing data like vectors across threads. Rust provides tools such as Arc and Mutex to safely share vectors in concurrent environments. In this session, we’ll cover how to share vectors between threads and explore parallel iteration.

Sharing Vectors Across Threads with Arc and Mutex

When you need to share a vector across threads, using Arc (atomic reference counting) and Mutex (mutual exclusion) allows safe access to the vector.

use std::sync::{Arc, Mutex};

use std::thread;



fn main() {

    let numbers = Arc::new(Mutex::new(vec![1, 2, 3]));

    let mut handles = vec![];



    for _ in 0..3 {

        let numbers = Arc::clone(&numbers);

        let handle = thread::spawn(move || {

            let mut data = numbers.lock().unwrap();

            data.push(42);

        });

        handles.push(handle);

    }



    for handle in handles {

        handle.join().unwrap();

    }



    println!("{:?}", *numbers.lock().unwrap());

}

Parallel Iteration with rayon

The rayon crate enables parallel iteration over vectors, which can significantly boost performance in certain workloads. Here’s how you can use it:

use rayon::prelude::*;



fn main() {

    let numbers: Vec<i32> = (1..=100).collect();

    let sum: i32 = numbers.par_iter().sum();

    println!("Sum: {}", sum);

}

Conclusion

Rust’s tools like Arc and Mutex ensure thread safety when sharing vectors across multiple threads. The rayon crate makes it easy to perform parallel operations on vectors, improving performance for certain workloads.

Comments