簡體   English   中英

如何在 Python 中讓 n 個線程永遠同時運行?

[英]How to have n threads running simultaneously forever in Python?

我正在嘗試擁有它,以便我可以在無限期的固定時間間隔內向 API 發出許多 HTTP 獲取請求。 我的想法是創建一個線程池並限制它的大小,並且只有在線程池有一個線程終止時,程序才會向它添加另一個線程。

經過一些研究,我遇到了這個問題, 這個問題和最重要的答案給出了一個解決方案,該解決方案僅在您想要發出有限數量的 GET 請求而不是無限數量時才有效。

引用問題的最佳答案:

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循環,但這樣做意味着線程池的隊列會增長到無窮大,並且計算機將產生 memory 錯誤。

如何在不依賴隊列系統的情況下僅在線程完成后將線程添加到池中?

像這樣使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM