我不知道我怎么会限制这样的事情也只能使用10个线程在同一时间python如何设置线程限制?
with open("data.txt") as f:
for line in f:
lines = line.rstrip("\n\r")
t1 = Thread(target=Checker, args=("company"))
t1.start()
我不知道我怎么会限制这样的事情也只能使用10个线程在同一时间python如何设置线程限制?
with open("data.txt") as f:
for line in f:
lines = line.rstrip("\n\r")
t1 = Thread(target=Checker, args=("company"))
t1.start()
使用Python的ThreadPoolExecutor有max_workers参数设置为10
事情是这样的:`
pool = ThreadPoolExecutor(max_workers=10)
with open("data.txt") as f:
for line in f:
lines = line.rstrip("\n\r")
pool.submit(Checker,"company")
pool.shutdown(wait=True)
的pool
将根据需要自动分配线程,限制分配的最大数量为10。第一个参数在pool.submit()
是函数名称,参数只是以逗号分隔的值传递。
pool.shutdown(wait=True)
等待所有线程完成执行。
使用ThreadPoolExecutor
,并告诉它你要10个线程。
def your_function_processing_one_line(line):
pass # your computations
with concurrent.futures.ThreadPoolExecutor(10) as executor:
result = executor.map(your_function_processing_one_line, [line for line in f])
...,你将不得不在result
所有结果。
如果多个参数? –
这也是可能的。看看[这个很好的答案](https://stackoverflow.com/questions/6785226/pass-multiple-parameters-to-concurrent-futures-executor-map/6976772#6976772)。 – yogabonito
(对于Python的2.6+和Python 3)
使用threadPool
从multiprocessing
模块:
from multiprocessing.pool import ThreadPool
的唯一的事情是,它没有很好的记载......
我编写了这个嵌套循环来将线程限制为一个变量。 此代码依赖于预设的命令数组进行处理。 我从其他答案中借用了一些元素来启动线程。
import os, sys, datetime, logging, thread, threading, time
from random import randint
# set number of threads
threadcount = 20
# alltests is an array of test data
numbertests = len(alltests)
testcounter = numbertests
# run tests
for test in alltests:
# launch worker thread
def worker():
"""thread worker function"""
os.system(command)
return
threads = []
t = threading.Thread(target=worker)
threads.append(t)
t.start()
testcounter -= 1
# cap the threads if over limit
while threading.active_count() >= threadcount:
threads = threading.active_count()
string = "Excessive threads, pausing 5 secs - " + str(threads)
print (string)
logging.info(string)
time.sleep(5)
# monitor for threads winding down
while threading.active_count() != 1:
threads = threading.active_count()
string = "Active threads running - " + str(threads)
print (string)
logging.info(string)
time.sleep(5)
只是监视线程活着并阻塞,直到其中一个线程退出,如果有10个或更多。 – ForceBru
可能的重复[如何限制在Python中的活动线程数量?](http://stackoverflow.com/questions/1787397/how-do-i-limit-the-number-of-active-threads-in -python) – zondo
[Python线程池类似于多处理池?]可能重复(http://stackoverflow.com/questions/3033952/python-thread-pool-similar-to-the-multiprocessing-pool) –