【问题标题】:Doesn't ThreadPoolExecutor start a new thread before the last thread is finishedThreadPoolExecutor 不会在最后一个线程完成之前启动一个新线程
【发布时间】:2021-03-01 08:14:03
【问题描述】:

我已经在 Colab 上写下了这个

import threading
import time
import os

class thread():
    def __init__(self, url, id, sleep_time):
        self.url = url
        self.id = id
        self.sleep_time = sleep_time

    def run(self, key):
        print("Task Executed {}".format(threading.current_thread()))
        self.upload_image(key)

    def upload_image(self, key):
        for i in range(10):
          print(self.id, "->", key)
          print()
          time.sleep(10)

with ThreadPoolExecutor(max_workers=1000) as executor:
  for i in range(1000):
    t = thread("url", i, 0.5)
    print("start the id: ", i)
    executor.submit(t.run("gg"))

无论何时运行最后一个线程,它都会休眠 10 秒,然后再执行下一次打印。但是,当前一个线程正在运行时,该程序不会启动新线程。比如线程 0 正在运行,并且休眠了 10 秒,那么程序在执行线程 0 时不应该启动线程 1 吗?

【问题讨论】:

    标签: python multithreading threadpoolexecutor


    【解决方案1】:

    你没有告诉执行者运行方法,你是在执行自己。

    executor.submit(t.run("gg"))
    

    这将评估t.run("gg") - 即在提交之前执行函数。

    你需要告诉执行者要执行什么,而不是执行它:

    executor.submit(t.run, ("gg",))
    

    在这里我告诉它使用 t.run 的参数来做 ("gg",)

    结果:

    start the id:  0
    Task Executed <Thread(ThreadPoolExecutor-0_0, started 123145503694848)>
    0 -> ('gg',)
    
    start the id:  1
    Task Executed <Thread(ThreadPoolExecutor-0_1, started 123145520484352)>
    1 -> ('gg',)
    ...
    

    【讨论】:

      【解决方案2】:

      我认为问题在于下面的代码行

      executor.submit(t.run("gg"))
      

      参考:https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.submit 关于如何将参数传递给 then 函数运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多