Python限制允许的线程数

时间:2017-02-20 00:05:22

标签: python multithreading

对于下面的代码段,我想将运行线程的数量限制为20个线程。我这样做的尝试似乎有缺陷,因为一旦计数器命中20,它就不会创建新线程,但“a”的那些值不会触发do_something()函数(必须考虑数组中的每个“a”) )。任何帮助是极大的赞赏。

count = 0
for i in range(len(array_of_letters)):

    if i == "a":
        if count < 20:
            count=+1 
            t = threading.Thread(target=do_something, args = (q,u))

            print "new thread started : %s"%(str(threading.current_thread().ident))     
            t.start()
            count=-1

1 个答案:

答案 0 :(得分:1)

concurrent.futures有一个ThreadPoolExecutor类,允许提交许多任务并指定最大工作线程数:

with ThreadPoolExecutor(max_workers=20) as executor:
    for letter in array_of_letters):
        executor.submit(do_something, letter)

查看软件包文档中的更多示例。

相关问题