Make a function time out in a parfor loop
Show older comments
This is not a question but rather an answer as I found no information on this topic anywhere but it took some time work out how to do it and I thought other people might have the same problem.
Essentially, I want to execute some code within a parfor loop but want to allow a maximum amount of time to do this. If the code hasn't finished running by then, I want to skip that iteration of the parfor loop. This proved a bit more tricky when done inside a parfor loop. The following code works for me under R2023b.
It is essential that you call parfeval with 'backgroundPool' in this case (else it runs it serial) and the desired behaviour is lost!
timeout = 5;
parfor a = 1:10
tic
F = parfeval(backgroundPool,@testfunction,3,a,b);
while 1
if toc > timeout && ~isequal(F.State, "finished")
fprintf('Interrupted after %0.2f seconds\n', toc)
cancel(F)
break
elseif isequal(F.State, "finished")
fprintf("Finished in time - %0.2f seconds\n", toc)
break
end
end
end
where testfunction is the following function with a random pause of maximum 10 seconds:
function [c, d, e] = testfunction(a, b)
c = a+b;
d = a-b;
e = a*b;
duration = rand(1)*10; % Set a random pause time of between 0 and 10 seconds
pause(duration);
end
1 Comment
Walter Roberson
on 29 Jul 2025
Note that in order for this to work, the regular parfor has to be the process pool while the parfeval is the background pool.
If the regular parfor is in the background pool, then there is the possibility that all of the available background pools are in use and so there would be no slots available to run the parfeval(), so it would remain queued until canceled.
... Though it is not really clear from the documentation whether a background pool thread is able to call parfeval...
Accepted Answer
More Answers (0)
Categories
Find more on Profile and Improve Performance 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!