hashy
hashy

Reputation: 305

main thread not execute until child thread finished

Basically, I have a program where I want to create a thread for executing certain function next to main thread. But in python it seems that when I create a thread, until the create thread hasn't finished, the execution is not passed to main thread.

See the following example:

import threading
import time


def testing():
    time.sleep(30)


wt = threading.Thread(target=testing, name="test", daemon=True)
print("Starting thread")
wt.start()
wt.join()
print("do other stuff next to above thread")

If you run above program, until the testing function has not finished, the main program does not print do other stuff next to above thread.

Not sure if I am missing some parameter or what, but can someone tell me how to create a thread that let the main program keep its execution continue?

Upvotes: 0

Views: 526

Answers (1)

Carlos E Jimenez
Carlos E Jimenez

Reputation: 91

Calling wt.join() makes the script stop and wait for wt to finish. If you want to run other things while wt is running, don't call wt.join() until later.

Try out this code to see:

import threading
import time

def testing():
    print('in testing()')
    time.sleep(5)

wt = threading.Thread(target=testing, name="test", daemon=True)
print("Starting thread")
wt.start()
print("do other stuff next to above thread")
wt.join()
print('after everything')

Upvotes: 2

Related Questions