如何在python中延迟启动线程
我创建了线程,在函数中增加了延迟,但所有线程都同时执行。相反,我希望线程一个接一个地开始。可能吗? 下面是我的代码如何在python中延迟启动线程,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我创建了线程,在函数中增加了延迟,但所有线程都同时执行。相反,我希望线程一个接一个地开始。可能吗? 下面是我的代码 from _thread import start_new_thread import time def mul(n): time.sleep(1) res = n * n return res while 1: m = input("Enter number ") t = input("Enter the number of t
from _thread import start_new_thread
import time
def mul(n):
time.sleep(1)
res = n * n
return res
while 1:
m = input("Enter number ")
t = input("Enter the number of times the function should be executed:")
max_threads = int(t)
for n in range(0, max_threads):
start_new_thread(mul, (m,))
except:
pass
print("Please type only digits (0-9)")
continue
print(f"Started {max_threads} threads.")
首先,您在线程内部添加了延迟,导致它在启动后暂停。因此,您将毫不延迟地一个接一个地启动所有线程,当每个线程启动时,它将等待1秒后再继续 因此,如果您希望在主线程中启动每个线程后添加特定的延迟 如果希望每个线程在前一个线程完成后启动,可以执行以下操作:
import threading
.
.
.
for n in range(0, max_threads):
t = threading.Thread(target = mul, args=(m,))
t.start()
t.join() # Waits until it is finished
什么是线程导入开始新线程的
?您应该在堆栈溢出中使用threading
moduleread,这不需要关闭线程