Python 与 start() 相关的多线程性能问题

Python multi-threading performance issue related to start()

我在使用多线程代码并行化多个 telnet 探测时遇到了一些性能问题。

我的第一个实现真的很慢,如果任务是 运行 顺序也是一样:

for printer in printers:
    …
    thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
    threads.append(thread)

for thread in threads:
    thread.start()
    thread.join()

极快

for printer in printers:
    …
    thread = threading.Thread(target=collect, args=(task, printers_response), kwargs=kw)
    threads.append(thread)
    thread.start()  # <----- moved this

for thread in threads:
    thread.join()

问题

我不明白为什么移动 start() 方法会对性能产生如此大的影响。

在您的第一个实现中,您实际上是按顺序 运行 代码,因为通过 调用 join() immediately after start() 主线程被阻塞 直到启动的线程完成。

在你的慢速解决方案中,你基本上根本没有使用多线程。 Id 是 运行 一个线程,等待完成它然后 运行 另一个 - 运行 一个线程中的所有内容和这个解决方案没有区别 - 你是 运行 它们串联.

另一方面,第二个启动所有线程,然后加入它们。此解决方案将执行时间限制为单个线程的最长执行时间 - 你是 运行 它们并行。

thread.join() 会在您的第一个实现中创建每个线程时立即阻止它们。

根据 threading.Thread.join() 文档:

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".

在您的 slow 示例中,您启动线程并等待它完成,然后迭代到下一个线程。

例子

from threading import Thread
from time import sleep


def foo(a, b):
    while True:
        print(a + ' ' + b)
        sleep(1)

ths = []

for i in range(3):
    th = Thread(target=foo, args=('hi', str(i)))
    ths.append(th)


for th in ths:
    th.start()
    th.join()

生产

hi 0
hi 0
hi 0
hi 0