duarte
duarte

Reputation: 23

daemon behaviour multiprocessing multithreading

from multiprocessing import Process
from threading import Thread

def main():

    thread1 = myclass(varA)   #subclassed threading.Thread
    thread1.daemon = False
    thread1.start()

    thread2 = Thread(target=myfunc)
    thread2.daemon = False
    thread2.start()

    while True:
        time.sleep(1)


if __name__ == "__main__":

    SUBPROCESS = Process(target=main)
    SUBPROCESS.daemon = False
    SUBPROCESS.start()

Why does the script die unless I add the while True: sleep in main()? (both thread1 and thread2 have functions that run forever) Shouldn't the daemon = False, keep them alive (the subprocess AND the subthreads in that subprocess) even when the parent process has ended?

EDIT1 (Working code)(have a look at the comments on Method A or method B, comment block one of the sections when running):

from multiprocessing import Process
from threading import Thread
import time


varA = "XYZ"

class myclass(Thread):

    def __init__(self, varA):
        Thread.__init__(self)
        self.varA = varA

    def run(self):
        while True:
            print("myClass prints %s" %self.varA)


def myfunc():
    while True:
        print("myfunc prints")



def main():

    thread1 = myclass(varA)   #subclassed threading.Thread
    thread1.daemon = False
    thread1.start()

    thread2 = Thread(target=myfunc)
    thread2.daemon = False
    thread2.start()


if __name__ == "__main__":

    #METHOD A: Running as subprocess = subthreads in that subprocess will die
    SUBPROCESS = Process(target=main)
    SUBPROCESS.daemon = False
    SUBPROCESS.start()


    #METHOD B: Running as main process = subthreads in that subprocess wont die as desired
    thread1 = myclass(varA)   #subclassed threading.Thread
    thread1.daemon = False
    thread1.start()

    thread2 = Thread(target=myfunc)
    thread2.daemon = False
    thread2.start()

Upvotes: 0

Views: 54

Answers (1)

user2357112
user2357112

Reputation: 281968

This was Python issue 18966; multiprocessing processes didn't join non-daemon threads before shutdown. The behavior has been changed in Python 3.7.0 so processes now join their non-daemon threads.

Upvotes: 1

Related Questions