Python Threads对象追加到列表

tud*_*uya 2 python multithreading

我在python中学习多线程。我经常看到程序使用多线程时,它将线程对象附加到一个列表中,如下所示:

# 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()
Run Code Online (Sandbox Code Playgroud)

我认为将线程对象追加到列表是一种好习惯,但是我不知道为什么要这样做?

dan*_*451 6

这是惯例。以您的示例为例:

# 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()
Run Code Online (Sandbox Code Playgroud)

可能需要等待每个线程完成其工作:

for thread in threads:  # iterates over the threads
    thread.join()       # waits until the thread has finished work
Run Code Online (Sandbox Code Playgroud)

如果不将线程存储在某些数据结构中,则必须手动进行操作(创建,启动,连接...):

thread_1 = threading.Thread(target=worker)
(...)
thread_n = threading.Thread(target=worker)

thread_1.start()
(...)
thread_n.start()

thread_1.join()
(...)
thread_n.join()
Run Code Online (Sandbox Code Playgroud)

如您所见(并可以想象):使用线程越多,如果您手动处理每个线程,就会创建更多的“文书工作”。这很快会带来太多麻烦。另外,您的代码将更加混乱并且难以维护。