通过多线程并行执行字典列表函数
在编写多线程程序时,您可以使用 threadpoolexecutor 线程池来高效地分配和管理工作线程。本例中,您的目标是使用多线程并行执行一个函数,该函数接受一个字典参数列表。
为了实现这一点,请遵循以下步骤:
下面的 python 代码展示了如何使用 threadpoolexecutor 来并行执行字典列表函数:
from concurrent.futures import ThreadPoolExecutor import threading my_list = [ {'ip': '192.168.1.2', 'password': '123456', 'user_name': '654321'}, {'ip': '192.168.1.3', 'password': '123456', 'user_name': '654321'}, {'ip': '192.168.1.4', 'password': '123456', 'user_name': '654321'}, {'ip': '192.168.1.5', 'password': '123456', 'user_name': '654321'}, {'ip': '192.168.1.6', 'password': '123456', 'user_name': '654321'} ] def dosome(ip, password, user_name): tname = threading.current_thread().getName() time.sleep(1) print(f'{tname} {ip}') tpe = ThreadPoolExecutor(max_workers=3) for m in my_list: tpe.submit(dosome, **m)
在上面的代码中,threadpoolexecutor 被配置为使用 3 个工作线程。对于列表中的每个字典,submit 方法将创建一个新的线程并执行 dosome 函数,传递字典中的参数作为函数参数。
以上就是如何使用 ThreadPoolExecutor 并行执行字典列表函数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号