如何在python中延迟启动线程

问题描述 投票:0回答:1

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

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.")

python multithreading python-multithreading
1个回答
0
投票

首先,您在线程内部添加了延迟,导致它在启动后暂停。因此,您正在一个一个一个地启动所有线程而没有延迟,并且每个线程启动时都会等待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
    
© www.soinside.com 2019 - 2024. All rights reserved.