Reputation: 469
I am learning multi-thread in python.I often see when the program use multi thread,it will append the thread object to one list, just as following:
# imports
import threading
import time
def worker():
print "worker...."
time.sleep(30)
threads = []
for i in range(5):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
I think append the thread object to list is good practice, but I don't know why should we do this?
Upvotes: 6
Views: 29325
Reputation: 10992
This is common practice. Taking your example:
# imports
import threading
import time
def worker():
print "worker...."
time.sleep(30)
threads = []
for i in range(5):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
One might want to wait for every thread to finish its work:
for thread in threads: # iterates over the threads
thread.join() # waits until the thread has finished work
Without storing the threads in some data structure you would have to do it (create, start, join, ...) manually:
thread_1 = threading.Thread(target=worker)
(...)
thread_n = threading.Thread(target=worker)
thread_1.start()
(...)
thread_n.start()
thread_1.join()
(...)
thread_n.join()
As you see (and can imagine): the more you work with the threads, the more "paperwork" would be created if you handle every thread manually. This fastly gets too much of a hassle. Additionally your code would be more confusing and less maintainable.
Upvotes: 15