Spawning scoped threads

I'm trying to fill up a large matrix in parallel, processing each row in a separated thread. Each thread and row is independent, so there is no conflict between different threads accessing the same row.

I have a working code using Arc and Mutex, however, there seems to be no need for it and I've read that it could be solved using scoped threads.

I'm trying to implement scoped threads, but am stuck with a cannot borrow as mutable sort of error. A minimal code in playground shows the error.

How to pass row into the worker function in a scoped thread?

You need to split iters into multiple non-overlapping mutable references before you spawn the tasks, and you have to do so using methods that the compiler understands produces non-overlapping slices. For example, using mutable iterators to get a mutable reference to each row:

thread::scope(|scope| {
    for row in &mut iters {
        scope.spawn(move || {
            worker(row);
        });
    }
})

Other common ways of splitting up iter is split_at_mut, or for more complicated cases, the rayon crate.

Using iters[i] doesn't work because it's required for thread-safety that each iteration uses different rows. Although that is the case for iters[i], the borrow-checker does not attempt to reason about indexing math, so the borrow-checker is not able to convince itself that it's okay, and therefore you get an error.

3 Likes