问题
I want to use threads to do some blocking work. What should I do to:
- Spawn a thread safely
- Do useful work
- Wait until the thread finishes
- Continue with the function
Here is my code:
import threading
def my_thread(self):
# Wait for the server to respond..
def main():
a = threading.thread(target=my_thread)
a.start()
# Do other stuff here
回答1:
You can use Thread.join. Few lines from docs.
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
For your example it will be like.
def main():
a = threading.thread(target = my_thread)
a.start()
a.join()
来源:https://stackoverflow.com/questions/25967093/how-to-wait-for-a-spawned-thread-to-finish-in-python