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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With