nested for inside parfor, writing to shared variable
2 ビュー (過去 30 日間)
古いコメントを表示
I want to do:
parfor ...
count;
for ...
if ...
count += 1
Do I need to worry about a race condition in this situation?
0 件のコメント
回答 (1 件)
Edric Ellis
2020 年 5 月 1 日
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 件のコメント
Edric Ellis
2020 年 5 月 1 日
You said "That would not work" - I'm not sure which "that" you are referring to. It would be really helpful if you could post some code that you think has a race condition. None of the code you have posted so far does so far as I can tell.
parfor puts language restrictions in place that essentially prevent race conditions. Loop iterations are required to be independent - this is enforced by language analysis of the result variables. If you really want to, you can make order-dependent parfor loops by hiding state in persistent variables in functions that you call from within parfor. Also, as I explained, error cases might leak some minor non-determinism.
I don't know if this helps: each iteration of a parfor loop is performed by a single worker. In fact, the parfor loop is divided up into "subranges" consisting of several iterations of the loop. Normally this is handled automatically by the parfor machinery, but in rare cases it can be useful to give extra direction to parfor about how you'd like things to be divided up. This is documented here.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!