How do I wait for a spawned thread to finish in python?
I am a newbie with threads in python. I need help on how I should: - create a thread - do useful work - wait for the thread to finish - do useful work
I'm not sure how safe I am creating a thread. You may need help with this.
import threading
def my_thread(self):
#wait for the server to respond..
#.....
# I want to rung this method aside from my main task
def main():
a = threading.thread(target = my_thread)
a.start()
# do some useful stuff here.....
# i.e opening a file and reading a file
# now I want to wait for my_thread to finish
# HOW DO I WAIT FOR my_thread to finish????????
# do some useful stuff here.....
+3
source to share
1 answer
You can use Thread.join
. Several lines from the docs.
Wait for the thread to finish. This blocks the calling thread until the thread whose join () method completes - either normally or through an unhandled exception - or until an additional timeout occurs.
For your example, it would look similar.
def main():
a = threading.thread(target = my_thread)
a.start()
a.join()
+5
source to share