Python Code Example: start threads in correct order (join-Keyword)

This code creates two thread objects, myFirstThread and mySecondThread, both executing the same startThread function. The function simply prints “Started thread…” and waits for 2 seconds using sleep, then prints “Done”. The main thread then starts both threads, waits for them to finish using join, and calculates the total time taken using perf_counter. Finally, it prints the string representation of the two threads, and the string “Time: [elapsed time in seconds] seconds”.

from threading import Thread
from time import sleep, perf_counter


def startThread():
    print("Started thread...")
    sleep(2)
    print("Done")


start = perf_counter()

myFirstThread = Thread(target=startThread)
mySecondThread = Thread(target=startThread)

myFirstThread.start()
mySecondThread.start()

myFirstThread.join()
mySecondThread.join()

end = perf_counter()
time = end - start

print(myFirstThread)
print(mySecondThread)
print("Time: " + str(round(time, 5)) + " seconds")
Output

The exact output would depend on the behavior of the threads, but it could look something like this:

Started thread...
Started thread...
DoneDone

<Thread(Thread-7, stopped 123145540182016)>
<Thread(Thread-8, stopped 123145556971520)>
Time: 2.01055 seconds