I'm still learning how to use multithreading, and I'm confused about how the join()
method works.
based on what I read, the join()
method stops everything until the thread terminates. but take a look at this code:
from threading import Thread
def do_something(i):
print("Sleeping...")
time.sleep(i)
print(f"Done sleeping {i}")
start = time.perf_counter()
t1, t2 = Thread(target=do_something, args=(1,)), Thread(target=do_something, args=(10,))
t1.start()
t2.start()
t2.join()
print("t2 joined")
t1.join()
print("t1 joined")
And when we run this, it gave us the output below:
Sleeping...
Sleeping...
Done sleeping 1
Done sleeping 10
t2 joined
t1 joined
As you can see, I used t2.join()
right after starting both threads, but the first thing that got printed is Done sleeping 1
. But based on what I thought join()
will do, I expected t1
to be stopped, and the program gave us the output below:
Sleeping...
Sleeping...
Done sleeping 10
Done sleeping 1
t2 joined
t1 joined
Can someone explain to me what I got wrong?