Unexpected behaviour in python multiprocessing
<p>I'm trying to understand the following odd behavior observed using the <code>python mutiprocessing</code>.</p>

<p>Sample testClass:
    import os
    import multiprocessing    </p>

<pre><code>class testClass(multiprocessing.Process):    

    def __del__(self):
        print "__del__ PID: %d" % os.getpid()
        print self.a    

    def __init__(self):
        multiprocessing.Process.__init__(self)
        print "__init__ PID: %d" % os.getpid()
        self.a = 0    

    def run(self):
        print "method1 PID: %d" % os.getpid()
        self.a = 1
</code></pre>

<p>And a little test program:
    from testClass import testClass    </p>

<pre><code>print "Start"
proc_list = []
proc_list.append(testClass())
proc_list[-1].start()    

proc_list[-1].join()    

print "End"
</code></pre>

<p>This produces:</p>

<pre><code>Start
__init__ PID: 89578
method1 PID: 89585
End
__del__ PID: 89578
0
</code></pre>

<p>Why it does not print <code>1</code>? </p>

<p>I'm guessing that it's related to the fact that <code>run</code> is actually being executed on a different process as can be seen. If this is the expected behavior how is everyone using multiprocessing where processes have an expensive <code>__init__</code> as in processes that need to open a database?</p>

<p>And shouldn't this behaviour be better highlighted in multiprocessing documentation?</p>

<p>You can wrap your expensive initialization inside a context manager:</p>

<pre><code>def run(self):
    with expensive_initialization() as initialized_object:
        do_some_logic_here(initialized_object)
</code></pre>

<p>You will have a chance to properly initialize your object before calling <code>do_some_logic_here</code>, and to properly release the resources after leaving the context manager's block.</p>

<p>See <a href="https://docs.python.org/3.6/reference/datamodel.html#context-managers" rel="nofollow">documentation</a>.</p>

python python-multiprocessing