如何使用多线程并行处理列表里的字典参数?
如何使用多线程处理列表中字典参数传递给函数
问题背景
拥有大量字典参数的列表,需要逐个传递给dosome(ip, password, user_name)函数并运行。自定义线程数量,例如,以 2 为单位并发执行参数传递。
解决方案
采用threadpoolexecutor线程池实现多线程处理:
import timefrom concurrent.futures import ThreadPoolExecutorimport threadingmy_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)
执行流程