Assigning handle classes in a parfor loop
Show older comments
I have been doing some calculations which are output by assigning data to a handle class array. The calculations run fine when I use a for loop but when I try to parallelise this by conversion to a parfor loop, the assigned data are no longer there when the parfor loop ends.
The documentation alludes to this as follows: "Changes made to handle classes on the workers during loop iterations are not automatically propagated to the client."
This implies that it may be possible for such changes to be propagated back, even if it's not done automatically. Does anyone know how I might do this?
Here is some example code:
classdef Example < handle
properties
data
end
methods
function obj = Example(data)
obj.data = data;
end
function setData(obj,data)
obj.data = data;
end
function data = getData(obj)
data = obj.data;
end
end
end
Now here is some example code which generates an array of these objects and then assigns values to them in a parfor loop. Finally we look at the values of the data.
% Function to demonstrate use of Example in a parfor loop
function testExample num = 5;
% Initialise array of objects
for n = 1:num
exArray(n) = Example(zeros(1,6));
end
% Set data within a parfor loop
parfor n = 1:num
setData(exArray(n),n:n+5);
end
% Now look at assigned data
for n = 1:num
disp(getData(exArray(n)));
end
end
When I run this code without the matlabpool open, it behaves as expected:
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
But when I run with matlabpool open, the updated values are lost outside of the parfor loop, giving this result:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Does anyone have any idea how to get around this problem, other than by not using parfor?
3 Comments
Daniel Shub
on 20 Jan 2012
Some additional information about your object and what you are setting would be helpful. Is it a scalar object? How are you currently setting the property?
Andrew
on 20 Jan 2012
tsan toso
on 22 Oct 2013
Hi Andrew,
Out of curiosity, could you also use the parfor loop when you first initialize the example class? to make things faster?
-tsantoso
Accepted Answer
More Answers (0)
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!