nested for inside parfor, writing to shared variable

6 views (last 30 days)
chris g
chris g on 30 Apr 2020
Commented: chris g on 1 May 2020
I want to do:
parfor ...
count;
for ...
if ...
count += 1
Do I need to worry about a race condition in this situation?

Answers (1)

Edric Ellis
Edric Ellis on 1 May 2020
parfor knows how to handle "reduction" variables like this correctly. (Behind the scenes, each worker process accumulates a partial summation for "count", and then at the end of the loop execution, the partial summations are sent back to the client where the final result is computed.) So, the following loop works as expected:
count = 0;
parfor i = 1:N
for j = 1:N
if i < j
count = count + 1;
end
end
end
count
  5 Comments
chris g
chris g on 1 May 2020
Perfect, thank you!
I apologize, I must have poorly phrase the original question. I was trying to ask if the pseudocode I posted had a race condition in it. I couldn't find any information how the workload was actually divided up among the workers, so I couldn't tell if there was a race condition. I probably should have just asked that in the first place.

Sign in to comment.

Tags

Products


Release

R2013b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!