当前位置: 代码网 > it编程>前端脚本>Python > Python使用线程池传递多个参数的几种方法

Python使用线程池传递多个参数的几种方法

2026年04月14日 Python 我要评论
在 python 中使用线程池传递多个参数有多种方法,以下是几种常用的方式:方法一:使用zip和*解包from concurrent.futures import threadpoolexecutor

在 python 中使用线程池传递多个参数有多种方法,以下是几种常用的方式:

方法一:使用zip和*解包

from concurrent.futures import threadpoolexecutor

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")
    # 这里执行实际的投屏操作

def thread_pool_with_zip():
    phones = ["172.26.101.164", "172.26.101.112", "172.26.101.113"]
    x_positions = [100, 500, 900]  # x坐标
    y_positions = [100, 100, 100]  # y坐标
    durations = [20, 25, 30]  # 投屏时长
    
    with threadpoolexecutor(max_workers=3) as executor:
        # 使用zip打包参数,然后解包传递给worker函数
        executor.map(worker, phones, x_positions, y_positions, durations)

方法二:使用partial函数固定部分参数

from concurrent.futures import threadpoolexecutor
from functools import partial

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_partial():
    phones = ["172.26.101.164", "172.26.101.112", "172.26.101.113"]
    
    # 固定x, y, duration参数
    fixed_worker = partial(worker, x=100, y=100, duration=20)
    
    with threadpoolexecutor(max_workers=3) as executor:
        executor.map(fixed_worker, phones)

方法三:使用字典或元组包装参数

from concurrent.futures import threadpoolexecutor

def worker(params):
    phone = params['phone']
    x = params['x']
    y = params['y']
    duration = params['duration']
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_dict():
    # 参数列表
    params_list = [
        {'phone': "172.26.101.164", 'x': 100, 'y': 100, 'duration': 20},
        {'phone': "172.26.101.112", 'x': 500, 'y': 100, 'duration': 25},
        {'phone': "172.26.101.113", 'x': 900, 'y': 100, 'duration': 30}
    ]
    
    with threadpoolexecutor(max_workers=3) as executor:
        executor.map(worker, params_list)

方法四:使用starmap(推荐)

from concurrent.futures import threadpoolexecutor

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_starmap():
    # 参数元组列表
    args_list = [
        ("172.26.101.164", 100, 100, 20),
        ("172.26.101.112", 500, 100, 25),
        ("172.26.101.113", 900, 100, 30)
    ]
    
    with threadpoolexecutor(max_workers=3) as executor:
        # 使用starmap解包元组参数
        executor.map(lambda args: worker(*args), args_list)

在您的代码中应用

修改您的代码以支持多参数传递:

def scrcpy(params):
    """接收参数字典的投屏函数"""
    phone = params['phone']
    x = params.get('x', 100)  # 默认值
    y = params.get('y', 100)  # 默认值
    duration = params.get('duration', 20)  # 默认值
    
    restartscrcpy(phone)
    time.sleep(5)
    phone_num = phone_number(phone)
    
    try:
        _ip_connext = f"{phone}:12324"
        run_cmd(f"adb connect {_ip_connext}")  
        # 添加窗口位置参数
        run_cmd(f'scrcpy -s {_ip_connext} --time-limit {duration} --max-size=1280 --window-title={phone_num} --window-x={x} --window-y={y}') 
        run_cmd(f"adb disconnect {_ip_connext}")
    except exception as e:
        log(logging.error, f"scrcpy: {e}")

def thread_pool_multiple_params():
    # 定义设备及其参数
    device_configs = [
        {'phone': "172.26.101.164", 'x': 100, 'y': 100, 'duration': 20},
        {'phone': "172.26.101.112", 'x': 800, 'y': 100, 'duration': 25},
        # 添加更多设备...
    ]
    
    try:
        with threadpoolexecutor(max_workers=len(device_configs)) as executor:
            executor.map(scrcpy, device_configs)
    except exception as e:
        log(logging.error, f"线程池异常: {e}")

# 在主函数中使用
if __name__ == '__main__':
    while true:
        if len(phones) >= 2:
            selected = random.sample(phones, 2)
            log(logging.debug, f"--> 随机选取的投屏设备:{selected}")
            
            # 为每个设备创建参数配置
            configs = []
            for i, phone in enumerate(selected):
                configs.append({
                    'phone': phone,
                    'x': 100 + i * 700,  # 水平排列窗口
                    'y': 100,
                    'duration': 20
                })
            
            thread_pool_multiple_params()
            time.sleep(5)
        # ... 其他条件判断

使用进程池(multiprocessing.pool)的多参数传递

import multiprocessing

def worker(args):
    phone, x, y, duration = args
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def multiprocessing_pool_multiple_params():
    args_list = [
        ("172.26.101.164", 100, 100, 20),
        ("172.26.101.112", 500, 100, 25),
        ("172.26.101.113", 900, 100, 30)
    ]
    
    with multiprocessing.pool(processes=3) as pool:
        pool.map(worker, args_list)

推荐方案

对于您的场景,我推荐使用方法四(starmap方式),因为它:

  1. 代码清晰易读
  2. 参数传递灵活
  3. 易于维护和扩展

这样您就可以为每个设备指定不同的窗口位置、投屏时长等参数了。

到此这篇关于python使用线程池传递多个参数的几种方法的文章就介绍到这了,更多相关python线程池传递多个参数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com