python列表内有很多字典参数,需要传递给执行函数运行,我想使用多线程运行,线程数是可以自定义的,我应该怎么实现这个功能?

  • 我有一个列表字典:

    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):
      run.....

我应该怎么使用多线程进行传递参数并运行dosome(ip,password,user_name)?并且线程数我是可以设置的,比如,我线程数设置2个,第一次2个线程执行

dosome(ip='192.168.1.2',password='123456',user_name='654321')
dosome(ip='192.168.1.3',password='123456',user_name='654321')

上线线程跑完了才开始执行后面的

dosome(ip='192.168.1.4',password='123456',user_name='654321')
dosome(ip='192.168.1.5',password='123456',user_name='654321')

直到最后执行完所有的列表内的字典参数

dosome(ip='192.168.1.6',password='123456',user_name='654321')
阅读 1.6k
1 个回答

ThreadPoolExecutor线程池即可

# -*- coding: UTF-8 -*-

__author__ = 'lpe234'

import time
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)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题