Home > database >  Perfectly parallel problems in Rust
Perfectly parallel problems in Rust

Time:11-03

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.

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

CodePudding user response:

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.

  • Related