我正在创建一个 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/

10-11 23:19
查看更多