限制Python中的线程数量

2024-10-08 23:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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))来限制线程的最大数量。我的问题是:

  • 假设我将线程数量限制为10,并且我的CSV文件中有15行,那么前10行肯定会被服务。我怎样才能把其他5个放在一边呢?一旦前10个路由器(线程)中的任何一个都完成了,我如何才能让这5行在以后得到服务?在

提前谢谢!在

卢卡斯


Tags: 文件csvinipfor数量len路由器
1条回答
网友
1楼 · 发布于 2024-10-08 23:25:17

您可以使用concurrent.futures.ThreadPoolExecutormultiprocessing.pool.ThreadPool来完成此操作。在不知道MiThread在做什么的情况下,很难确切地告诉您如何实现它,但是基本思想如下(使用multiprocessing.pool.ThreadPool):

def run_mi_thread(i, CliLine, ip):
    # Do whatever MiThread.run does.


oFile = csv.reader(open(FileCsv,"r"), delimiter=",", quotechar="|")
routers = list(oFile)
[. . .]
p = ThreadPool(5) # 5 threads
for i, router in enumerate(routers):
    # We generate the config file
    ip = router[0]
    CliLine= write_cliLine(router)
    p.apply_async(run_mi_thread, args=(i, CliLine, ip))
p.close()
p.join()

使用此方法,最多将运行五个并发操作。您的所有其他请求将由ThreadPool在内部排队,并将在池中的线程完成任务时逐个从队列中弹出。在

注意,我删除了启动线程之间的延迟。如果需要,可以将其添加回去,但只能保证前N个任务正常工作,其中N是池中的线程数。在

相关问题 更多 >

    热门问题