How can I write a parallel for loop in a function that returns for all workers as soon as a condition is met?
I.e. something like this:
function test(n)
@sync @parallel for i in 1:1000
{... statement ...}
if {condition}
return test(n+1)
end
end
end
where all the workers stop working on the for loop and only the main process returns? (and the other processes start again working with the next for loop?)
The question seems like a basic pattern for doing "embarrassingly parallel" search tasks. The
@parallel for
construct is good for partitioning work, but doesn't have thebreak
short-circuit logic for stopping as thefor
in single process flow.To demonstrate how to do this in Julia consider a toy problem of finding the combination of a combination lock with several wheels. Each setting of a wheel can be checked for correctness with some method (taking a
combodelay
time - see code below). After the correct number for a wheel is found, the next wheel is searched. The high level pseudo code is like the snippet given in the OP question.The following is running code (on 0.5 and 0.6) to do this. Some comments explain details, and the code is given in a single chunk for easy cut-and-paste.
There could be better looking implementations, and some meta-programming can hide some of the short-circuit machinery. But this should be good as a start.
Results should look approximately like this:
This is calculated for demonstration with 3 worker processes. Real problems should have many more processes and more work per process and then the benefits of short-circuiting will be evident.