Vector values differ if accessed outside or from within parfor

我与影子孤独终老i 提交于 2019-12-07 06:22:40

问题


I have created this test Matlab script file:

numbers = [29 37 44 54 62];

for i=1:length(numbers)
    fprintf('%d\n', numbers(i));
end

fprintf('***\n');

matlabpool local 5;
parfor i=1:length(numbers)
    fprintf('%d\n', numbers(i));
end % image loop
fprintf('***\n')
for i=1:length(numbers)
    fprintf('%d\n', numbers(i));
end
matlabpool close;

fprintf('***\n');

for i=1:length(numbers)
    fprintf('%d\n', numbers(i));
end

When I run it, I get consistently the following output:

29
37
44
54
62
***
112
111
107
117
115
***
29
37
44
54
62
***
29
37
44
54
62

The fprintf within the parfor block prints the seemingly random set of numbers which is, however, always the same (112, 111, 107, 117, 115). Any idea as to why this is happening?

UPDATE

Interestingly enough, this only happens if I run the script from command line:

matlabR2012b -nodesktop -nosplash -nodisplay -r "run parfortest.m; exit"

If I first open a Matlab session and run parfortest there, then the numbers are printed correctly.


回答1:


This is specifically a problem with run and not a nodesktop issue. To verify this, you can try

>> run parfortest.m

from the MATLAB desktop and you'll find the same output.

Although it's not a solution as such; if you omit run, and just use

>> parfortest

the bad output will be corrected.




回答2:


I can replicate it too on OS X, R2012b. In mex, mexPrintf is not thread safe. See this. I wouldn't be surprised if Matlab's fprintf relies on mexPrintf - or similar code - under the hood. If you turn your script into a function - just put function parfortest on the first line - the problem goes away, so it may also be a scoping issue.

EDIT: Try printing more than five numbers, say twelve of them. Now use char to convert these values to ASCII characters. It looks like, in the parfor loop fprintf is printing out the path to the file you ran via the Terminal command (some form of parfortest.m in a randomish order - I ran the file from ~/Desktop/parfortest.m and converting the number from fprintf to chars I got D/~ksepotap/frroetst.m). If you try to print more values than the length of the path then you'll get an error. I can't find a workaround other than turn your script into a function (which is a good idea anyways). Definitely seems like a bug.




回答3:


I guess you can't really parallel write a file. Or in this case the output screen since fprintf("text") implies fprintf(1,"text") where 1 is the fileID for the output screen.

The file is now being modified by multiple processes which is a problem because the used buffer is not being flushed before other operations start and the behaviour will be erratical.

Maybe this link will help.



来源:https://stackoverflow.com/questions/16944433/vector-values-differ-if-accessed-outside-or-from-within-parfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!