Multithreading library in matlab
6 views (last 30 days)
Show older comments
Hi,
My question is simple, is there a way to run threads in matlab like in cpp using <thread> or <pthread> standard library.
Thx in advance !
0 Comments
Answers (1)
Jan
on 4 May 2021
No. You can use the command parfor and spmd, but this does not match the C++ threads exactly.
4 Comments
Raymond Norris
on 13 Oct 2021
Edited: Raymond Norris
on 13 Oct 2021
At the time of Walter's writing, he's right. With that said, in R2021b we've now released backgroundPool, which can execute on a separate thread if you don't have Parallel Computing Toolbox or up to 8 threads with Parallel Computing Toolbox.
Walter Roberson
on 13 Oct 2021
Communicating to/from background threads is still weak. Background threads are invoked through the parfeval() mechanism, which involves passing in a function handle, and passing in a list of parameters.
Background evaluation does not read from the environment; you cannot access the base workspace, and globals are not copied into the background.
Notice that the global I set in one thread is not always available on the next run, but is sometimes. This is likely due to the pool generated here having 4 workers: if setting globals works inside an individual worker until the worker is destroyed, but the globals are not copied between workers, then you would expect this behaviour, that the change does not become visible until the worker ends up getting re-used (you cannot choose the worker.)
From past experience, the behaviour of globals tells me that it is quite likely that device objects are not being copied into the background space, and so need to be created in the background space.
To send back data from a background thread, maybe it would work to create a dataqueue and pass it into the thread as a parameter. But that would require the Parallel Computing Toolbox if it were going to work at all.
global AAA
AAA = 'this is a global';
BBB = 'this is a local in the base workspace'
P = backgroundPool
tests = {@testbackground1, @testbackground2, @testbackground3, @testbackground3, @testbackground3, @testbackground3, @testbackground3};
for K = 1 : length(tests)
F = parfeval(P, tests{K}, 1)
try
fetchOutputs(F)
catch ME
fprintf('well, test #%d did not work', K)
end
end
delete(P)
function out = testbackground1
out = BBB; %refering to base workspace
end
function out = testbackground2
out = evalin('base', 'BBB'); %refering to base workspace explicitly
end
function out = testbackground3
global AAA;
out = AAA; %refering to explicit global
AAA = 'new value set in background'
end
See Also
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!