Multithreaded computation on one variable

Hi. I was playing around with "multithreading computation" and I was trapped by Rust's strict "memory safety regulations."

What I wanted to achieve was simple. I had an array of size n of f64s, and I wanted to take advantage of multithreading to speed up some time-consuming, in-place computation tasks (doesn't really matter what the tasks actually were, just add 1 to each f64 instead). I divided the array as evenly as possible into num_cpu chunks and send them to num_cou threads to run concurrently. Since no data-overlapping problem would ever occur, I would assume that no overhead should be introduced (such as Locks or Rcs).

I tried to play around split_at_mut(), but unfortunately I didn't get my code compiled successfully. Can anyone provide any advice or a minimal working sample? (assumes that the function looks like below)

fn compute(arr: &mut [f64]) { // please modify arr in-place


1 Like

Better to flip that around, I think -- what did you try, and what were the problems? You're on the right track with split_at_mut().

In my (biased) opinion, rayon is best for this. :slight_smile:


You may want to have a look at rayon, It's really good with data parallelization.

Simple Example:

use rayon;
use rayon::prelude::*;

fn compute(data: &mut [f64]) {
    data.par_iter_mut().for_each(|x| *x += 1.0);

fn main() {
    let mut data = [0f64; 10];
    for i in 0..10 {
        data[i] = i as f64;
    compute(&mut data);

Thanks for pointing that out, I will definitely give it a try. But I somehow still prefer to do it manually (just for familiarizing Rust concurrency).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.