[python, multiprocessing] Behavior for exceptions when using multiprocessing

Although multiprocessing is used for parallel processing in Python, the behavior when a child process is created by multiprocessing has some differences from the behavior of a normal function call.

Preparation

This time, the function sleep_bug () is used for simplicity. This is a function that executes 1 / 0 at ʻi == 5` to generate an error in order to intentionally generate an error during execution.

import time

def sleep_bug():
    for i in range(10):
        print('sleeping %d' % i)
        if i == 5:
            1/0
        time.sleep(1)
    return i

sleep_bug()

 output
'''
sleeping 0
sleeping 1
sleeping 2
sleeping 3
sleeping 4
sleeping 5
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-44-d9f02a4cf7f3> in <module>
----> 1 sleep_bug()

<ipython-input-41-26bb27998e63> in sleep_bug()
     12         print('sleeping %d' % i)
     13         if i==5:
---> 14             1/0
     15         time.sleep(1)
     16 

ZeroDivisionError: division by zero
'''

If the child process makes an error, the parent process will continue to run.

In a normal function call, if an error occurs in the called function, the program will stop there. However, if you let a child process created using Pool execute sleep_bug (), the child process will stop with an error, but the parent process will proceed to the end without any error.

from multiprocessing import Pool
p = Pool(1)
r = p.apply_async(sleep_bug)
p.close()
 p.join () # Wait for the child process to finish.
print('Done')

 output
'''
sleeping 0
sleeping 1
sleeping 2
sleeping 3
sleeping 4
sleeping 5
Done
'''

Use r.get () to make the error propagate to the parent process when the child process stops due to an error. r.get () is a function that normally waits for the child process to terminate and outputs the return value of the child process, but if an error occurs in the child process, r.get () Will throw an exception and the parent process will also stop there.

from multiprocessing import Pool
p = Pool(1)
r = p.apply_async(sleep_bug)
p.close()
output = r.get()
print('Done %d' % output)

# output
'''
sleeping 0
sleeping 1
sleeping 2
sleeping 3
sleeping 4
sleeping 5
---------------------------------------------------------------------------
RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "<ipython-input-41-26bb27998e63>", line 14, in sleep_bug
    1/0
ZeroDivisionError: division by zero
"""

The above exception was the direct cause of the following exception:

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-50-fb8f5892e1a7> in <module>
      3     r = p.apply_async(sleep_bug)
      4     p.close()
----> 5     output = r.get()
      6     print('Done %d' % output)

/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py in get(self, timeout)
    655             return self._value
    656         else:
--> 657             raise self._value
    658 
    659     def _set(self, i, obj):

ZeroDivisionError: division by zero
'''

If you use Process, an error will be displayed, but the parent process will proceed to the end.

from multiprocessing import Process
p = Process(target=sleep_bug)
p.start()
p.join()
print('Done')

# output
'''
sleeping 0
sleeping 1
sleeping 2
sleeping 3
sleeping 4
sleeping 5
Process Process-35:
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
    self.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-41-26bb27998e63>", line 14, in sleep_bug
    1/0
ZeroDivisionError: division by zero
Done
'''

The child process keeps running even if the parent process stops

In the script below, the child process waits 2 seconds while it is running, and the parent process terminates itself there with sys.exit (). As shown in the execution example below, even if the parent process stops in the middle, the child process continues to run.

from multiprocessing import Pool
p = Pool(1)
r = p.apply_async(sleep)
p.close()
 r.wait (2) #wait 2 seconds for child process
sys.exit()

# output
'''
sleeping 0
sleeping 1
An exception has occurred, use %tb to see the full traceback.

SystemExit
sleeping 2
sleeping 3
sleeping 4
sleeping 5
sleeping 6
sleeping 7
sleeping 8
sleeping 9
'''

Recommended Posts

[python, multiprocessing] Behavior for exceptions when using multiprocessing
Check the behavior when assigning Python
Behavior when listing in Python heapq
[TouchDesigner] Tips for for statements using python
[Python] Be careful when using print
[Python] Reasons for overriding using super ()
[Python] Multiplication table using for statement
Precautions when using phantomjs from python
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
[VS Code] ~ Tips when using python ~
When using regular expressions in Python
Things to watch out for when using default arguments in Python
Effective Python Note Item 17 Respect for certainty when using iterators for arguments
Python development environment for macOS using venv 2016
Periodic execution processing when using tkinter [Python3]
[50 counts] Key transmission using Python for Windows
Favicon placement (when using Python, Flask, Heroku)
Precautions when using for statements in pandas
Tips for using python + caffe with TSUBAME
Notes for using python (pydev) in eclipse
A memo when setting up a Docker container for using JUMAN ++, KNP, python
A useful note when using Python for the first time in a while
python [for myself]
vprof --I tried using the profiler for Python
How to take multiple arguments when doing parallel processing using multiprocessing in python
Python pandas: Search for DataFrame using regular expressions
[python, CPython] GC behavior when throwing an exception
Start using Python
Get note information using Evernote SDK for Python 3
Precautions when using tf.keras.layers.TimeDistributed for tf.keras custom layer
Character encoding when using csv module of python 2.7.3
Refined search for Pokemon race values using Python
Things to keep in mind when using Python for those who use MATLAB
[For beginners] Unexpected behavior if "\" is included when setting the path in Python
Let's make a module for Python using SWIG
Behavior when saving python datetime object in MongoDB
Scraping using Python
[Python] Notes on accelerating genetic algorithms using multiprocessing
What are you using when testing with Python?
Let's analyze Covid-19 (Corona) data using Python [For beginners]
Initial settings for using Python3.8 and pip on CentOS8
Searching for pixiv tags and saving illustrations using Python
Extendable skeletons for Vim using Python, Click and Jinja2
Directory structure for test-driven development using pytest in python
Precautions when using sqlite3 on macOS Sierra (10.12) with multiprocessing
Initial settings when using the foursquare API in python
[Python for Hikari-] Chapter 07-01 Exception Handling (Errors and Exceptions)
[Heroku] Memo for deploying Python apps using Heroku on Windows [Python]
Error due to conflict between python when using gurobi
Check types_map when using mimetypes on AWS Lambda (Python)
Explore Alibaba Cloud Function Compute for DevOps using Python 3.0
Installation method when using RealSense from Python (pyenv edition)
Causes when python version cannot be changed using pyenv
Troublesome story when using Python3 with VScode on ubuntu
How to exit when using Python in Terminal (Mac)
Where to fix code when using plotly for free
Error when executing Python commands without using Anaconda Prompt
Articles to see when installation for Python + OpenCV fails
Minimum memo when using Python on Mac (pyenv edition)
Memo for building a machine learning environment using Python