[英]How to create multiple threads dynamically in Python
I am creating a python code that have a function which should be run for number of times user asks using threads. 我正在创建一个python代码,该代码具有一个功能,该功能应运行用户要求使用线程的次数。 Eg:
例如:
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)
Based on the value of T from user, I want tho create T' number of threads dynamically and execute the sum function in separate threads. 基于用户的T值,我想通过动态创建T'个线程并在单独的线程中执行sum函数。
If user gives input as 4 then I need to create 4 threads dynamically and execute the same function with 4 different threads. 如果用户输入为4,则需要动态创建4个线程,并使用4个不同的线程执行相同的功能。 Please help me out to create 4 multiple threads.Thanks!
请帮我创建4个多线程。谢谢!
It depends on your needs, you have several ways to do. 这取决于您的需要,您有几种方法可以做。 Here is two examples suitable for your case
这是两个适合您情况的示例
If you want to create N
threads and wait for them to end. 如果要创建
N
线程并等待它们结束。 You should use the threading
module and import Thread
. 您应该使用
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()
Otherwise, in case you do not want to wait. 否则,以防万一您不想等待。 I strongly advise you to use the
thread
module (renamed _thread
since Python3) . 我强烈建议您使用
thread
模块(自Python3起更_thread
_thread) 。
from _thread import start_new_thread
# Start all threads and ignore exit.
for n in range(T):
start_new_thread(sum, (L,))
(args,)
are a tuple. (args,)
是一个元组。 It's why L
is in parantheses. 这就是
L
处于括号中的原因。
SU П Σ Y Λ answer explains well how to use multi-threading, but didn't take into account user input, which, according to your question, defines the number of threads. SUПΣYΛ答案很好地解释了如何使用多线程,但没有考虑用户输入,用户输入根据您的问题定义了线程数。 Based on that, you can try:
基于此,您可以尝试:
import threading, time
def _sum(n):
time.sleep(0.2)
print(f"square: {n*n}")
while 1:
t = input("Enter the number of times the function should be executed:\n").strip()
try:
max_threads = int(t)
for n in range(0, max_threads):
threading.Thread(target=_sum, args=[n]).start()
except:
pass
print("Please type only digits (0-9)")
continue
print(f"Started {max_threads} threads.")
# wait threads to finish
while threading.active_count() > 1:
time.sleep(0.5)
t = input("Create another batch (y/n)?\n").lower().strip() #
if t != "y":
print("Exiting.")
break
Notes: 笔记:
sum()
, use _sum()
or similar name; sum()
,使用_sum()
或类似名称; Def
isn't the same as def
, the same goes For
/ for
; Def
与 def
, For
/ for
; '
or double quotes "
, not '
; '
或双引号"
,而不是 '
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.