How do you get out of parallel loops? ParallelBreak

in the next fragment, if you replace Do by ParallelDo, it will be evaluated 3 times SLOWER, because now the cycle will be broken only in ONE of two cores.

ParallelEvaluate[NN = 10070];
SetSharedVariable[res]
Module[{a, b, c},
  Do[
   c = NN - a - b;  
   If[a a + b b == c c, res = a b c; Break[]]
   , {a, 1, NN}, {b, a + 1, NN}
   ];
  res
  ] // AbsoluteTiming

Calling ParallelAbort will solve the problem, but it is forbidden. What else do you have?

+3
source share
1 answer

You need to have a way for each iteration to tell all other iterations that the answer has been found. I modeled this using the "quit" flag embedded in false, which is set to true when any iteration decides to end. Each iteration also has an exit condition for checking.

Mathematica 15 , Parallelxxx, :

ParallelEvaluate[NN = 10070];
SetSharedVariable[res,quit]
Module[{a, b, c},
    quit=false;
   Do[ c = NN - a - b;  
       If[quit, Break[]];
       If[ a a + b b == c c, quit=true; res = a b c; Break[]],
       {a, 1, NN}, {b, a + 1, NN}
     ];
     res
   ] // AbsoluteTiming

If , .

, , , , , , , Do Parallel. , a b (, {a, 1, NN, 10} b 10- ). , . .

: . res. , , res "", . res Mathematica, , . - . , MMa, , " [...]" , . (, MMa , . , :

ParallelEvaluate[NN = 10070];
SetSharedVariable[res,quit]
Module[{a, b, c},
    quit=false;
   Do[ c = NN - a - b;  
       If[quit, Break[]];
       If[ a a + b b == c c, 
           atomic[If[not[quit]; quit=true; res = a b c;]; Break[]],
       {a, 1, NN}, {b, a + 1, NN}
     ];
     res
   ] // AbsoluteTiming
+3

Source: https://habr.com/ru/post/1715429/


All Articles