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