Search code examples
pythonmultithreadingfunctionpython-multithreading

How to implement right threading execution order in python?


I recently started studying threads in python, and I ran into this problem: I need the "two" function to finish executing after executing the function one in the thread, but the join method does not work, apparently because of the while true loop in the third function. I tried using queue, but it didn't work either.

the code itself:

from threading import Thread,Event

def one():
    event.set()
    thr.join()
    for i in range(3):
        print('some print')
        time.sleep(1)

def two():
    t = Thread(target=one)
    t.start()
    #with t.join() here the program does not work at all, same thing with event.set()
    print('func two finished')

def three(callback, event):
    c = 0
    while True:
        c += 1
        time.sleep(1)
        print('func 3 is working')
        if c == 5:
            two()
        if event.is_set():
            callback(c)
            print('func 3 is stopped')
            break

def callback(t):
    print('callback ',t)

def thread(callback):
    global event, thr
    event = Event()
    thr = Thread(target=three, args=(callback, event,))
    thr.start()
    thr.join()

thread(callback)

current output:

func 3 is working
func 3 is working
func 3 is working
func 3 is working
func 3 is working
func two finished
callback  5
func 3 is stopped
some print
some print
some print

expected:

func 3 is working
func 3 is working
func 3 is working
func 3 is working
func 3 is working
callback  5
func 3 is stopped
some print
some print
some print
func two finished

Solution

  • Your program creates a deadlock if you un-comment that t.join() call in function two;

    • The thr thread cannot finish until after the t thread has finished because the thr thread calls t.join() in function two.

    • The t thread cannot finish until after the thr thread has finished because the t thread calls thr.join() in function one.

    Neither thread can finish until after the other thread finishes. Therefore, neither thread can ever finish.


    Why does one join the thr thread?

    def one():
        event.set()
        thr.join()           # What were you trying to do here?
        for i in range(3):
            print('some print')
            time.sleep(1)
    

    Your program will give the output you wanted if you comment out that join call, and uncomment the t.join() call in function two.