我有一个python脚本,可以触发多个到不同路由器的并行telnet连接来执行某些操作。效果很好。路由器列表在CSV文件中传递给python。在
另一方面,为了触发并行telnet连接,我使用线程。我的代码是这样开始的:
oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|")
routers = list(oFile)
[. . .]
for i in range(len(routers)):
# We generate the config file
ip = routers[i][0]
CliLine=write_cliLine(routers[i])
# running routine
t = MiThread(i,CliLine,ip)
# wait random number of seconds between threads (0sec to 5sec)
time.sleep(random.randint(0,5))
t.start()
今天,线程的数量由CSV文件(for i in range(len(routers))
)内的行数给出。我知道我可以通过限制for循环(for i in range(10)
)来限制线程的最大数量。我的问题是:
提前谢谢!在
卢卡斯
您可以使用
concurrent.futures.ThreadPoolExecutor
或multiprocessing.pool.ThreadPool
来完成此操作。在不知道MiThread
在做什么的情况下,很难确切地告诉您如何实现它,但是基本思想如下(使用multiprocessing.pool.ThreadPool
):使用此方法,最多将运行五个并发操作。您的所有其他请求将由
ThreadPool
在内部排队,并将在池中的线程完成任务时逐个从队列中弹出。在注意,我删除了启动线程之间的延迟。如果需要,可以将其添加回去,但只能保证前N个任务正常工作,其中N是池中的线程数。在
相关问题 更多 >
编程相关推荐