python - 如何在Python中动态创建多个线程

标签 python multithreading dynamic

我正在创建一个Python代码,它有一个函数,该函数应该运行用户使用线程请求的次数。例如:

import time
T = input("Enter the number of times the function should be executed")
L = [1,2,3,4]

def sum(Num):
    for n in Num:
        time.sleep(0.2)
        print("square:",n*n)

根据用户提供的 T 值,我希望动态创建 T 个线程并在单独的线程中执行 sum 函数。

如果用户输入为 4,那么我需要动态创建 4 个线程,并使用 4 个不同的线程执行相同的函数。 请帮我创建 4 个多线程。谢谢!

最佳答案

这取决于您的需求,您有多种方法可以做到。这是适合您的情况的两个示例

带有线程模块

如果你想创建N个线程并等待它们结束。您应该使用 threading 模块并导入 Thread

from threading import Thread

# Start all threads. 
threads = []
for n in range(T):
    t = Thread(target=sum, args=(L,))
    t.start()
    threads.append(t)

# Wait all threads to finish.
for t in threads:
    t.join()

带有线程模块

否则,如果您不想等待。我强烈建议您使用 thread 模块(自 Python3 起重命名为 _thread)

from _thread import start_new_thread

# Start all threads and ignore exit.
for n in range(T):
    start_new_thread(sum, (L,))

(args,) 是一个元组。这就是 L 位于括号中的原因。

关于python - 如何在Python中动态创建多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55529319/

相关文章:

python - 如何更改Word文档表格下单元格的字体颜色?

php - 从数据库中获取 ID 计数并生成指向新闻的动态链接

javascript - 从现有对象动态创建新的 javascript 类

java - 等待并通知协调

c# - 多线程 SQL 选择语句

c++ - 用 C++ 实现的可移植线程类

Java:使用动态加载的类

c++ - 使用 Python 从 C++ 程序中获取输出(通过 cout)

python - dataframe.hist()中参数 "bins"代表什么?

Python pandas 有效地删除 UserWarning 和循环