Search code examples
python-3.xmultithreadingpython-multithreading

Threading - Main thread running permanently and other threads are dependent on another


Im pretty new to python and threading. My goal was it to have one main thread that is running permanently and other threads that are dependent on another. I tried different things with .join() but i couldnt get an answer.

Here is a picture what ive come up with in my mind: Thread Imagination

Do i need something like a daemon or can i solve this with just simple .join()?


Solution

  • Try that structure:

    from threading import Thread
    from time import sleep
    
    def do_work_1():
        print("Thread 1 starting")
        sleep(1)
        print("Thread 1 done")
    
    def do_work_2(parent_thread):
        print("Thread 2 wait thread 1 to finish")
        parent_thread.join()
        print("Thread 2 starting")
        sleep(1)
        print("Thread 2 done")
    
    def do_work_3(parent_thread):
        print("Thread 3 wait thread 2 to finish")
        parent_thread.join()
        print("Thread 3 starting")
        sleep(1)
        print("Thread 3 done")
    
    thread1 = Thread(target=do_work_1)
    thread2 = Thread(target=do_work_2, args=(thread1,)) # Do not miss the comma!
    thread3 = Thread(target=do_work_3, args=(thread2,))
    
    thread1.start()
    thread2.start()
    thread3.start()
    
    for num in range(6):
        print("Main thread still do job", num)
        sleep(0.60)
    
    thread3.join()
    print("Job done")