文章内容

2021/2/3 10:41:29,作 者: 黄兵

python 多线程长时间运行程序

上一篇文章(python Thread长时间运行问题)使用python Thread的方式,长时间运行服务程序,会出现线程耗尽的问题。

之后又更改程序,使用concurrent.futures的方式运行程序,经过一晚上的测试,程序还算稳定,没有出现线程耗尽的问题,这篇文章整理和总结使用concurrent.futures长时间运行多线程程序的方法。

关键代码:

def ping_main(self):
ip_list = self.get_ip_list_by_csv()
workers = min(self._num_worker, len(ip_list))
with futures.ThreadPoolExecutor(workers) as executor:
to_do = []
for ip in ip_list:
future = executor.submit(self.ping, ip)
to_do.append(future)

for future in futures.as_completed(to_do):
future.result()

这里使用线程池的方式实现了多线程。

    workers = min(self._num_worker, len(ip_list))

Python min()函数返回可迭代的最小项。它还可以用于查找两个或多个参数之间的最小项。

这里返回一个较小的数作为线程数量。

之后使用ThreadPoolExecutor使用线程池异步调用。

今天早上查看运行程序的日志,看到如下错误:

ValueError: max_workers must be greater than 0

max_workers必须大于0,应该是刚才上面min()出现了问题,修改代码如下:

def ping_main(self):
ip_list = self.get_ip_list_by_csv()
# fix ValueError: max_workers must be greater than 0
workers = min(self._num_worker, len(ip_list) if len(ip_list) > 0 else 1)
with futures.ThreadPoolExecutor(workers) as executor:
to_do = []
for ip in ip_list:
future = executor.submit(self.ping, ip)
to_do.append(future)

for future in futures.as_completed(to_do):
future.result()

使用了三元运算符,设置线程数量,解决上面存在的问题。

同时运行了一晚上,内存占用也没有很高,截图如下:


题外话:

关于Concurrent.futures与Multiprocessing的异同可以参考这篇文章:在Python 3中Concurrent.futures 与 Multiprocessing 的区别


参考资料:

1、concurrent.futures --- 启动并行任务


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - python 多线程长时间运行程序

分享到:

发表评论

评论列表