Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中延迟启动线程_Python_Multithreading_Python Multithreading - Fatal编程技术网

如何在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,这不需要关闭线程