Parfor loop with classes and listerner

1 view (last 30 days)
I have 2 classes as follows:
classdef ToggleButton < handle
properties
rx_bits = [0;1;0;1;1];
iteration = 1;
end
events
ToggledState
end
methods
function new_iteration(obj, new_iterations, new_bits)
if new_iterations ~= obj.iteration
obj.iteration = new_iterations;
obj.rx_bits = new_bits;
notify(obj,'ToggledState');
end
end
end
end
classdef myClass < handle
properties
value
end
methods
function obj = myClass(toggle_button_obj)
addlistener(toggle_button_obj,'ToggledState',@(src,evnt)obj.evntCb(src,evnt));
end
function obj = evntCb(obj,src,~)
obj.value(src.iteration) = sum(src.rx_bits);
end
end
end
As it can be seen, the 1st class has an event which notifies the second class. There is a listener in the second class which waits for this notification, so once notified it updates its value property.
I am trying to execute this in a loop saving the values using the script:
rx = ToggleButton;
performance = myClass(rx);
for i = 1:10
rx.new_iteration(i,round(rand(2,1)*10))
end
If I execute the above I get the expected result and the property value is updated each iteration. However, if I change the for loop to parfor it does not work anymore. I do not get any error message but the property value is empty after execution.
Any suggestion on why this happens and how to fix it?

Accepted Answer

Walter Roberson
Walter Roberson on 21 Aug 2023

parfor operates in separate processes. The object is being loaded into the separate processes, and any changes to the object in the separate processes are not copied back.

rx will not be shared between the parfor workers.

  11 Comments
Sam Marshalik
Sam Marshalik on 24 Aug 2023
Miroslav, before doing that, I would suggest reaching out to MathWorks Technical support.
I think DataQueue could potentially help you here. It is capable of sending information between the workers and the MATLAB client and if set up properly can also accomadate worker to worker communication. This would enable your parfor workers to pass information to one another and may resolve this issue.
Walter Roberson
Walter Roberson on 24 Aug 2023
Dataqueues have historically been documented as not permitting worker to worker communication. There was always the question of what would happen if you constructed queues on the workers, sent them to the client, and the client sent them to the other workers, but the documentation always said no worker to worker was possible.

Sign in to comment.

More Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!