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

Shr*_*ri 5 python multithreading dynamic

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

\n\n
import time\nT = input("Enter the number of times the function should be executed")\nL = [1,2,3,4]\n\ndef sum(Num):\n    for n in Num:\n        time.sleep(0.2)\n        print("square:",n*n)\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n

Dot*_*ot. 7

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

带线程模块

如果你想创建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()
Run Code Online (Sandbox Code Playgroud)

带线程模块

否则,万一您不想等待。我强烈建议您使用该thread模块_thread自Python3起重命名)

from _thread import start_new_thread

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

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