MATLAB Answers

0

Communicate with worker through client

Asked by guy sharon on 22 Sep 2019
Latest activity Commented on by guy sharon on 25 Sep 2019
Hello!
I have an app (app designer/GUIDE) which calls a function that looks something like this
function func()
spmd
switch labindex
case 1
while (true)
% some code...
end
case 2
while (true)
% some code...
end
end
end
end
and I would like to be able to break out of the while loop for each workers of the spmd with a click of a button in the app, which means I have to send data from the client to the workers.
I know I can easily send data from the workers to the client, but I'm not sure about the reverse direction.
Please help, thanks!

  0 Comments

Sign in to comment.

1 Answer

Answer by Edric Ellis
on 23 Sep 2019

I think it would be better to use parfeval or parfevalOnAll to do this. This way, you can simply cancel the future object returned from those calls to stop the worker execution. You could couple this with a parallel.pool.DataQueue to get the results back from the workers. Here's a simple example:
% Build a really simple "UI" - just a histogram and a button
pool = gcp();
fig = uifigure();
grid = uigridlayout(fig, [1, 2]);
ax = axes(uipanel(grid));
btn = uibutton(grid);
hist = histogram(ax, 'BinEdges', 0.5 + (0:pool.NumWorkers));
% Set up a DataQueue to let the workers send results back to the client
Q = parallel.pool.DataQueue();
% Each time a worker sends a piece of data to the client, append it
% to the histogram
listener = afterEach(Q, @(data) appendData(hist, data));
% Trigger the work on the workers, hook up the future to the button
% so that pressing the button cancels 'fut'.
fut = parfevalOnAll(@doWork, 0, Q);
btn.ButtonPushedFcn = @(~,~) cancel(fut);
%% function to do work on the workers
function doWork(Q)
task = getCurrentTask;
myId = task.ID;
while true
send(Q, myId);
pause(myId/4);
end
end
%% function to append data to the histogram
function appendData(hist, data)
hist.Data(end+1) = data;
end

  3 Comments

Hi, Thank you for the answer.
However, I want to be able to have communication between the workers with labSend and labRecieve.
labSend and labReceive can only be used inside spmd. Unfortunately, spmd is a synchronous construct on the client, so there's no way for the client to interrupt the workers.
So there is no way to both be able to communicate between workers and be able to stop all workers from the client?

Sign in to comment.