如何不等待线程在Python中完成 [英] How NOT to wait for a thread to finish in Python
问题描述
在此问题中,他实际上问了一些我想要的东西.答案是删除括号.但是,如果删除括号,则将无法为函数传递参数.
In this question, he actually asked something like what I want. Except that the answer was to remove the parentheses. However if I remove the parentheses, then I'll not be able to pass arguments for my functions.
如何在不等待的情况下执行以下简单代码:
How can I do the following simple code without waiting:
from time import sleep
import threading
def whatever(i):
sleep(5)
print("Hey! It's me number " + str(i))
for i in range(3):
t = threading.Thread(target=whatever(i))
t.start()
所需的输出将是
Hey! It's me number 0
Hey! It's me number 1
Hey! It's me number 2
全部同时打印
推荐答案
在文档中,target
应该是可调用的:
target是run()方法要调用的可调用对象
target is the callable object to be invoked by the run() method
您没有将函数传递给target
,而是传递了函数的返回值,因此该函数在将其传递给threading.Thread
后立即运行,而不是在调用t.start()
时运行.
You are not passing your function to target
, you are passing the return value of your function, so the function runs as soon as you pass it to threading.Thread
, not when you call t.start()
.
您应该使用args
参数为可调用对象指定参数.
You should be using the args
parameter to specify arguments to your callable.
只需更改此行:
t = threading.Thread(target=whatever(i))
到
t = threading.Thread(target=whatever, args=(i,))
这篇关于如何不等待线程在Python中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!