parfor - can't get my head around it

why does the following code deliver an error..
clear all
n=10;
count=zeros(1,n);
b=round(rand(1,n)*10); %basically some arbitrary array
parfor i=1:length(b)
count(b(i))=count(b(i))+1;
end
count
whereas
count(i)=count(i)+1;
works fine. But I need to address different count-elements, any suggestions?
thanks for every hint in advance.

1 个评论

As always it would be helpful not only to post that there is an error, but the error message also.

请先登录,再进行评论。

回答(3 个)

Jan
Jan 2012-5-9

3 个投票

In your code Matlab cannot predict if a specific element of count is read and written at the same time. If this happens, the result is not predictable. In consequence the parallelization fails.
Daniel Shub
Daniel Shub 2012-5-9

0 个投票

The MATLAB parser (???) cannot tell that count can be sliced. The parser thinks that potentially b(i) might equal b(j) for some i not equal to j.
that b(i) might be the same makes actually sense. In fact, that is even the case occasionally since this rand-construction gives sometimes the same values. Thanks!
what I still do not understand is the following code:
% ...everything is defined in a way that a usual for works fine
for l = 1:length(y)
for k = 1:length(z)
r = [0 2 3]; %position
parfor i = 1:length(R)
for j = 1:length(d)
r0 = [0 0 d(j)];
Myfield = B_field_loop(n,r,r0,R(i));
B_y(l,k)= B_y(l,k) + Myfield(2);
B_z(l,k)= B_z(l,k) + Myfield(3);
end
end
end
end
the error than I get is :
??? Error: The variable B_y in a parfor cannot be classified.
(which, btw, is the same error as for the 'count'-example, but here the issue is a different one?! - since it is not possible that l and k are the same that two threads address the same element at the same time)
the problem is probably not very sophisticated, but I'm just not really used to matlab parallel stuff. thanks again for all comments.

2 个评论

If your original question has been answers please accept an answer and vote for helpful answers. If not, comment on the answers, edit your question, or continue waiting. You should post this "answer" as a new question. I think this one has work around, but I don't remember it.
What is B_field_loop? Imagine it is a function, which uses ASSIGNIN to overwrite the value of "k" by e.g. 14. Then again different PARFOR threads can access an element of B at the same time for reading and writing, such that the results are random.
Isn't there an exhaustive documentation for PARFOR which explains such tricky details?! Parallelizing functions is a very complicated job and avoiding a false sharing of variables is not trivial.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

标签

提问:

2012-5-9

Community Treasure Hunt

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

Start Hunting!

Translated by