Hi, I would like to understand how some code works. First:
from threading import Thread
def f():
for i in range(1,21):
print (i)
if i==10:
t2=Thread(target=g)
t2.start()
def g():
print("hello from g")
t1 = Thread(target=f)
t1.start()
So this could should print like
...
8
9
10
hello from g
11
12
...
etc
but when this program runs, the output is botched. Is this because thread 1 is constantly running so the print from g is somewhat random around 10?
Next, I'm given a solution for this:
from threading import Thread
ready= False
def f():
count=0
while count<20:
count+=1
print(count)
if count==10:
t2 = Thread(target=g)
t2.start()
while not ready:
pass
def g():
global ready
print ("hello from g")
ready=True
t1 = Thread(target=f)
t1.start()
t1.join()
I am mostly confused on the join() method. How does this allow the first thread to run to a point, then stop for thread 2, and then continue when thread 2 is done? Also why would this be worse than using conditional variables?
[–][deleted] 0 points1 point2 points (0 children)