【问题标题】:Call 4 methods at once in Python 3在 Python 3 中一次调用 4 个方法
【发布时间】:2023-01-15 07:49:48
【问题描述】:

我想一次调用 4 个方法,以便它们在 Python 中并行运行。这些方法进行 HTTP 调用并执行一些基本操作,如验证响应。我想立即给他们打电话,这样花费的时间会更少。假设每个方法需要大约 20 分钟来运行,我希望所有 4 种方法在 20 分钟而不是 20*4 80 分钟内返回响应

寻找建议

【问题讨论】:

  • 你似乎已经知道multithreading ...你试过了吗?向我们展示您到目前为止所做的尝试。

标签: python multithreading http asynchronous python-3.8


【解决方案1】:

你可以使用from concurrent.futures import ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor

def foo_1():
    print("foo_1")

def foo_2():
    print("foo_2")

def foo_3():
    print("foo_3")

def foo_4():
    print("foo_4")

with ThreadPoolExecutor() as executor:
  for foo in [foo_1,foo_2,foo_3,foo_4]:
    executor.submit(foo)

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    相关资源
    最近更新 更多