Search code examples
matlabparallel-processingparfor

Vector values differ if accessed outside or from within parfor


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.


Solution

  • 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.