如何延迟 python 启动线程

How to start threads with a delay in python

我创建了线程,在函数中添加了延迟,但所有线程都在同时执行。相反,我希望线程一个一个地开始。那可能吗 ? 下面是我的代码

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