簡體   English   中英

Python循環中的線程但具有最大線程

[英]Python threading in a loop but with max threads

現在我有一個循環遍歷列表的for循環,通常這個列表長100-500個項目。 for循環中,每個項目打開一個新線程。 所以現在我的代碼看起來像這樣:

    threads = []
    for item in items:
        t = threading.Thread(target=myfunction, args=(item,))
        threads.append(t)
        t.start()

但是我不希望每個線程啟動一個新線程,看到每個線程只需要幾秒鍾來執行myfunction。 我想繼續循環,在參數中調用每個項目的函數。 但是一旦完成就關閉線程,並允許另一個線程接管。 我要打開的最大線程數不少於3,不超過20.雖然如果更容易,但該范圍可能會有所不同。 我只是不想在循環中的每個項目中打開一個新線程。

對於那些好奇的人,如果重要的話。 myfunction是我定義的一個函數,它使用urllib向站點發送post請求。

我是python的新手,但我並不擅長編碼。 抱歉,這個菜鳥問題。

我認為你正在尋找一個線程池來解決你的問題。

這個問題的答案詳述了一些可能的解決方案。

其中一個最簡單的(假設python3或pypi中的backport)是:

from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(max_workers=10)
futures = []
for item in items:
    a = executor.submit(myfunction, item)
    futures.append(a)

這將使用10個線程為所有項執行myfunction。 您可以稍后使用期貨清單等待完成通話。

我相信你的問題在於缺少的功能。 它可能是一些問題,我推薦你訪問pythons主頁: https//goo.gl/iAZuNX

#!/usr/bin/python

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

稍微修改您的代碼以包括在任何給定時間檢查活動線程的數量:

threads = []
consumed_by_threads = 0
consumed_by_main = 0
for item in items:
    at = threading.activeCount()
    if at <= 20:
        t = threading.Thread(target=myfunction, args=(item,))
        threads.append(t)
        consumed_by_threads += 1
        t.start()
    else:
        print "active threads:", at
        consumed_by_main += 1
        myfunction(item)

print "consumed_by_threads: ", consumed_by_threads
print "consumed_by_main: ", consumed_by_main

# here the rest of your code, thread join, etc

注意:我只檢查最大線程數。 BTW:它應該是21,因為主線程包含在計數中(參見此處並按照enumerate的鏈接)

Nota Bene:像往常一樣,根據您使用的python實現以及線程是cpu綁定還是I / O綁定,仔細檢查多線程對特定應用程序的好處。

暫無
暫無

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

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