orbita
orbita

Reputation: 47

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+=stride) {
    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?

Upvotes: 0

Views: 148

Answers (1)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26549

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.

Upvotes: 2

Related Questions