Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Perfectly parallel problems in Rust

I’m struggling to see how I could best implement a common concurrency pattern I use in c++.

Pseudocode:

void kernel(inputs, outputs, start, stride) {
  for (size_t i = start; i < length(inputs); i++) {
    outputs[i] = process(inputs[i]);
  }
}
void run(inputs, number_of_threads) {
  threads = []
  vector outputs(length(inputs))
  for (int i = 0; i < number_of_threads; i++ {
    threads.push(thread(kernel, inputs, &outputs, i, number_of_threads));
  }
  for t in threads {
    t.join()
  }
return outputs
} 

That is, doing some function over lots of inputs by striding over the input space. It’s perfectly parallel, never has race conditions etc. But with rust’s ownership model, each kernel would need a mutable reference to outputs, so I don’t understand how it could work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s the safe way to do this simple problem in Rust?

>Solution :

You can use splice::split_at_mut to separate the array into separate sub-slices, each with their own mutable reference. You can pass the first slice to a scope‘d thread then continue splitting the second slice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading