Home > OS >  how do you make threads wait for eachother
how do you make threads wait for eachother

Time:03-22

okay so i'm trying to make a speedtest in python and the only problem i am having is that i cant figure out how to make the download speed threads finish before starting the upload speed threads. i can provide some of my code:

t1 = Thread(target= dload)
t2 = Thread(target= testo)
t3 = Thread(target= uload)
t4 = Thread(target= testo2)

t2.daemon=True
t4.daemon=True

t1.start()
t2.start()
t3.start()
t4.start()

i need t1 and t2 to end first, and then t3 and t4 should start. t2 is a daemon here because i want it to end as soon as t1 is done. forgot to mention that beforehand. i am completely new to threading so if this is really wrong please forgive me.

CodePudding user response:

You use join for that. Note that t2.daemon=True means that you expect t2 to not end while the script is running. This is in opposition to your specification that you want to wait for t2 to end.

t1 = Thread(target= dload)
t2 = Thread(target= testo)
t3 = Thread(target= uload)
t4 = Thread(target= testo2)

# t2.daemon=True
t4.daemon=True

t1.start()
t2.start()

# wait for t1 and t2 to end
t1.join()
t2.join()

t3.start()
t4.start()

CodePudding user response:

There are 2 ways to solve your problem:

  • Using .join method. (Effective and clean)
  • Using functions (Not as effective than .join)
  1. Using .join function : see this answer.
  2. Using function:
    • The basic idea is threading one function and just calling the other function.
    • And if you want to run testo until t1 ends, then you can watch a variable and run the inside while loop. for example:
while t1_ends==False: # Change this value to true in t1 fucntion at the end of it.
    testo() 
t1 = Thread(target= dload)
t2 = Thread(target= testo)
t3 = Thread(target= uload)
t4 = Thread(target= testo2)

t4.daemon=True
def a():
    t1.start()
    testo()
def b():
    t3.start()
    t4.start()

a()
b()
  • Related