Weird behaviour with threads and processes mixing
<p>I'm running the following python code:</p>

<pre><code>import threading
import multiprocessing

def forever_print():
    while True:
        print("")

def main():
    t = threading.Thread(target=forever_print)
    t.start()
    return


if __name__=='__main__':
    p = multiprocessing.Process(target=main)
    p.start()
    p.join()
    print("main process on control")
</code></pre>

<p>It terminates. </p>

<p>When I unwrapped <code>main</code> from the new process, and just ran it directly, like this:</p>

<pre><code>if name == '__main__':
    main()
</code></pre>

<p>The script went on forever, as I thought it should. Am I wrong to assume that, given that <code>t</code> is a non-daemon process, <code>p</code> shouldn't halt in the first case?</p>

<p>I basically set up this little test because i've been developing an app in which threads are spawned inside subprocesses, and it's been showing some weird behaviour (sometimes it terminates properly, sometimes it doesn't). I guess what I wanted to know, in a broader sense, is if there is some sort of "gotcha" when mixing these two python libs.</p>

<p>My running environment: python 2.7 @ Ubuntu 14.04 LTS</p>

<p>You need to call <code>t.join()</code> in your <code>main</code> function.</p>

<p>As your <code>main</code> function returns, the process gets terminated with both its threads.</p>

<p><code>p.join()</code> blocks the main thread waiting for the spawned process to end. Your spawned process then, creates a thread but does not wait for it to end. It returns immediately thus trashing the thread itself.</p>

<p>If Threads share memory, Processes don't. Therefore, the Thread you create in the newly spawned process remains relegated to that process. The parent process is not aware of it.</p>

python multithreading multiprocessing