How to run multiple functions simultaneously and communicate with each other?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello everyone. Here is my question:
Let's say I have 2 functions to run together with different but equal sized data. I want to call and run these functions simultaneously and in the future these functions are going to communicate with each other. So, based on my research I should work with spmd command. I have examined so many examples but I feel like I haven't figure out the command properly.
function a = aData()
a = 0;
for i = 1:100 a end
function b = bData()
b = 1;
for j = 1:100 b end
% To call them
parpool(2);
spmd
aData();
bData();
end
delete(gcp); % to avoid any error message
When I do this in the first place, I was expecting an output like : a b a b a b a b a b a b a b .. for 100 times.
Instead of that, I get a a a a a a a ... for 100 times and then b b b b b b b b... for 100 times.
Then I add a timer to hold aData for 10 seconds and check if bData is being called ahead for 10 seconds.
function a = aData()
a = 0;
T = timer('TimerFcn', @(~,~)disp('Fired.'), 'StartDelay', 10);
start(T)
wait(T)
for i = 1:100 a end
Didn't do any changes in bData function.
So I was expecting an output like : b b b b b b (for 10 s) a b a b a b a b a b a b .. a a a a a a (totaly 100 times each). But when I try the hold aData for 10 seconds, bData is also hold.
Here is what I get:
(No disp for 10 s)
After 10 s : b b b b b b // a a a a a a a (for 100 times) then b b b b b b b (for totally 100 times).
What am I doing wrong guys? Thanks in advance.
0 comentarios
Respuestas (1)
Edric Ellis
el 7 de Jun. de 2024
Your spmd block as written instructs each worker to run first aData() and then bData(). This is the general pattern of spmd - all workers execute the body simultaneously. If instead you want one worker to run aData() and the 2nd to run bData(), you should switch on the value of spmdIndex inside the spmd block, like this:
spmd
if spmdIndex == 1
aData();
elseif spmdIndex == 2
bData();
end
end
0 comentarios
Ver también
Categorías
Más información sobre Communications Toolbox en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!