【问题标题】:How to have n threads running simultaneously forever in Python?如何在 Python 中让 n 个线程永远同时运行?
【发布时间】:2021-05-05 10:40:48
【问题描述】:

我正在尝试使用它,以便我可以在不固定的时间间隔内以恒定的时间间隔向 API 发出大量 HTTP get 请求。我的想法是创建一个线程池并限制它的大小,并且只有在线程池有一个线程终止时,程序才会向它添加另一个线程。

经过一些研究,我遇到了thisthis 一个问题,最重要的答案给出了一个解决方案,该解决方案仅在您想要发出有限数量的 GET 请求而不是无限数量的情况下才有效。

引用that问题的最佳答案:

import threading
from multiprocessing.pool import ThreadPool

def test_thread(elem):
    return elem ** 2

a = [1,2,3,4,5,6,7,8]
pool = ThreadPool(2) # 2 worker threads
results = []
for x in range(8):
    print x
    results.append(pool.apply_async(test_thread, args=(a[x],)))

results = [result.get() for result in results]
# You can also replace this for loop altogether using pool.map
# and get the same result:
# results = pool.map(test_thread, range(8))
print(results)

我想将for x in range(8): for 循环更改为while True 循环,但这样做意味着线程池的队列会增长到无穷大,并且计算机会产生内存错误。

如何在不依赖队列系统的情况下仅将线程添加到池中?

【问题讨论】:

  • @python_user 谢谢你,但我已经完成了,我的问题是我会向池中添加太多线程并耗尽内存。
  • 您的问题是向池中添加了太多任务,而不是线程

标签: python python-multithreading


【解决方案1】:

像这样使用concurrent.futures 模块:

futures = set()
# prime the pump
for x in range(8):
    futures.add(pool.submit(test_thread, args=TODO))

# now keep it running with one new task per finished one
while True:
    done, futures = concurrent.futures.wait(futures,
        return_when=concurrent.futures.FIRST_COMPLETED)
    for x in done:
        futures.add(pool.submit(test_thread, args=TODO))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2023-03-27
    • 2013-02-07
    相关资源
    最近更新 更多