0

I want to kill all processes if I have an exception in a process. Here is the trial code.

import multiprocessing as mp;
import time;

def f(x):
  if x==1:
    raise Exception("job error");
  time.sleep(x*0.2);
  print x;
  return x*x;

if __name__ == '__main__':
  p = mp.Pool(processes=5);
  try:
    for i in [4,6,3,5,1]:
      p.apply_async(f, (i,));
  except Exception as e: # exception is not caught!
    print "catch",e;
    p.terminate();
  p.close();
  p.join();

However, the exception is not caught. How can I catch the exception in a process and terminate all processes? I'm using python 2.7.

nemy
  • 519
  • 5
  • 16
  • Does this answer your question? [Exception thrown in multiprocessing Pool not detected](https://stackoverflow.com/questions/6728236/exception-thrown-in-multiprocessing-pool-not-detected) – Mat.C Jan 10 '20 at 10:40
  • Check this https://stackoverflow.com/questions/6728236/exception-thrown-in-multiprocessing-pool-not-detected – Mat.C Jan 10 '20 at 10:40
  • It doesn't work. I can catch the exception only after all processes are finished. What I want to do is killing all processes as soon as the first exception is raised. – nemy Jan 10 '20 at 15:29
  • Instead of working with expections you can try to do a workoround – Mat.C Jan 10 '20 at 15:39

0 Answers0