You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何动态创建任意数量线程实时运行带不同参数的同一函数

动态创建多线程实现方案

首先修正你原有代码的一个隐藏问题:args参数传入的("1")本质是字符串,而非单元素元组,当参数长度不为1时会直接报参数数量错误,正确的单元素元组写法为("1",)。

实现动态数量线程的逻辑很简单,用列表存储线程实例,遍历参数列表批量创建即可,你需要多少个线程就往参数列表里加多少个对应参数,也可以在代码运行过程中随时按需创建新线程:

固定参数批量创建示例

import threading
import ctypes

def fun1(txt):
    return ctypes.windll.user32.MessageBoxW(0, txt, "title", 0)

# 自定义需要传入的参数列表,线程数量和参数一一对应
param_list = ["1", "2", "3", "第4个线程参数", "自定义内容"]
thread_pool = []

# 批量创建并启动线程
for param in param_list:
    t = threading.Thread(target=fun1, args=(param,))
    thread_pool.append(t)
    t.start()

# 若需要等待所有线程执行完成再执行后续逻辑,添加下方代码即可
for t in thread_pool:
    t.join()

实时动态创建示例

如果需要在程序运行过程中根据实际情况随时创建新线程,不需要提前定义参数列表,按需直接创建启动即可,比如以下是接收用户输入实时创建线程的示例:

import threading
import ctypes

def fun1(txt):
    return ctypes.windll.user32.MessageBoxW(0, txt, "title", 0)

while True:
    input_content = input("请输入弹框显示内容,输入q退出:")
    if input_content.strip() == "q":
        break
    # 每次接收到有效输入就实时创建一个新线程
    new_thread = threading.Thread(target=fun1, args=(input_content,))
    new_thread.start()

内容的提问来源于stack exchange,提问作者Arif Diggi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:09:05