'How do I write to a mutable slice from multiple threads at arbitrary indexes without using mutexes?

I have two slices that are passed from another method:

fn example<T>(a1: &[T], a2: &mut [T]) {}

I want to process a1 with multiple threads and then write to a2 using completely arbitrary indices that are only known when each thread is executed. The indices are guaranteed by my algorithm to be mutually exclusive, so there is no data race.

The borrow checker doesn't like sharing mutable references among threads since it doesn't know of the guarantee our algorithm makes. I also get a lifetime 'static required rustc (E0621) error.

So how to do this in Rust?

Answers to

Do not answer my question.

The answer to the first question addresses the scoping problem, but not the problem of accessing arbitrary mutually disjoint indexes. The answer to the second question suggests as_slice_of_cells but that doesn't work here because of the aforementioned reason, namely the arbitrary access. The answer to the third question similarly suggests as_slice_of_cells but again, the assumption that the array can be split into disjoint parts cannot be fulfilled here. The fourth question again asks about partitioning the array, which we cannot do here. And the same applies to the fifth question.

One answer to the scoping problem (https://stackoverflow.com/a/64502824/10056727) actually attempts to address this problem, but it doesn't suggest to use crossbeam and the alternative suggested is more unsafe than the top answer here.



Solution 1:[1]

How to do this in Rust? Resorting to unsafe is okay.

If you need two threads to mutate the same data, without locks, then you must use unsafe. It is Undefined Behaviour for two mutable references (&mut) to the same data to even exist, so you would need to access the data via *mut raw pointers, while being extremely careful to avoid data races.

However, depending on your algorithm, you may be able to avoid unsafe by creating non-overlapping &mut references with split_at_mut.

Solution 2:[2]

Here is a code using a Vector or AtomicI32 put into an Arc for doing what you need:

use std::sync::Arc;
use std::thread;

use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;

// ==================================================================
// ==================================================================
const SIZE: usize = 4;

// ==================================================================
// ==================================================================
fn new_worker( id: i32, // id for the thread
               a_data: Arc::<Vec<AtomicI32>> // Vec of i32 inside an arc-ptr
             ) -> thread::JoinHandle<()> {

    // create new thread
    // a_data is moved into the thread
    let hand = thread::spawn(move || {

        // a_data[id] <- 2 * id * a_data[id]
        // use load() for readng and store() for writing
        a_data[id as usize].store( 
            2 * id *
            a_data[id as usize].load( Ordering::Relaxed ),
            Ordering::Relaxed );
    });

    return hand;
} // ()

// ==================================================================
// ==================================================================
fn main() {
    let mut data : Vec<AtomicI32> = Vec::new(); //  vector of i32

    // populate the vector
    for _i in 0..SIZE {
        data.push( AtomicI32::new( 1 ) );
    } // for

    // put the array into an arc-ptr: move to the heap, share arc-ptr
    let data_arc = Arc::new(data);

    // share the data through the arc-ptr
    let hand1 = new_worker(1, data_arc.clone());
    let hand2 = new_worker(3, data_arc.clone());

    // wait for the threads to end
    hand1.join().unwrap();
    hand2.join().unwrap();

    // print their work
    println!( "2 == {:?}", data_arc[1].load( Ordering::Relaxed ) );
    println!( "6 == {:?}", data_arc[3].load( Ordering::Relaxed ) );
} // ()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 cibercitizen1