2015-06-12 112 views
3

现在我有一个for循环遍历列表,通常这个列表是100-500项长。在for循环中,每个项目打开一个新线程。所以现在我的代码看起来是这样的:Python线程在一个循环,但最大线程

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

但我不希望每次启动一个新的线程,看到只需要每个线程几秒钟MAX执行MyFunction的。我想继续做我的循环,在参数中调用每个项目的功能。但是一旦完成就关闭线程,并让另一个线程接管。我想打开的最大线程数不少于3,不超过20个。虽然如果更容易,那么范围可能会有所不同。我只是不想在循环中打开每个项目的新线程。

对于那些很好奇,如果它很重要。 myfunction是我定义的一个函数,它使用urllib向站点发送post请求。

我是python的新手,但我并不是全新编码在一起。对于noob问题抱歉。

+0

'threading.activeCount()'可以帮助你决定是否产生一个线程或者在那里执行'myfunction',然后将它传递给当前'item'。 – Pynchia

+0

好吧。那么我的代码看起来像threading.activeCount()> 20,而不仅仅是执行myfunction,否则启动线程? – user1687621

+0

是的,我已经添加了它作为答案,我花了一些时间来测试它 – Pynchia

回答

1

我相信你的问题在于缺失的功能。它可能是一个数量的问题,我建议您访问蟒蛇主页: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" 
+0

错误:无法启动线程 – Gank

3

我认为你正在寻找一个线程池来解决你的问题。

this question的答案详细说明了一些可能的解决方案。

最简单的(假设python3或pypi的反向移植)的是:

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的。您可以稍后等待使用期货清单完成呼叫。

1

稍微修改代码以包括在任何给定时间对活动的线程数量的检查:

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,因为主线程计算在内(见here并按照链接enumerate

诺塔Bene的:像往常一样,仔细检查一下多线程对特定的应用,根据受益在哪个python实现上使用以及线程是cpu绑定还是I/O绑定。