Multithreading library in matlab
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Jan
2021-5-4
No. You can use the command parfor and spmd, but this does not match the C++ threads exactly.
4 个评论
Raymond Norris
2021-10-13
编辑:Raymond Norris
2021-10-13
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
2021-10-13
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!