'how do you make threads wait for eachother
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.
Solution 1:[1]
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()
Solution 2:[2]
There are 2 ways to solve your problem:
- Using
.joinmethod. (Effective and clean) - Using functions (Not as effective than
.join)
- Using
.joinfunction : see this answer. - Using function:
- The basic idea is threading one function and just calling the other function.
- And if you want to run
testountil 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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wackazong |
| Solution 2 | Faraaz Kurawle |
