线程在调用Thread.start之前开始运行 [英] thread starts running before calling Thread.start
问题描述
t1=threading.Thread(target=self.read())
print("something")
t2=threading.Thread(target=self.runChecks(), args=(self,))
self.read
无限期运行,因此程序永远不会到达print
行.不调用t1.start()
怎么可能? (即使我叫它,它也会开始运行并继续到下一行,不是吗?)
self.read
runs indefinitely, so the program won't ever reach the print
line. How is this possible without calling t1.start()
? (Even if I call that, it shold start running and go on to the next line, shouldn't it?)
推荐答案
由于target=self.read()
上的尾随()
,您在错误的线程中运行了self.read
,而当前的 > thread(不是您正在创建的新线程),并将self.read
调用的返回值作为Thread
的target
自变量传递. Thread
希望传递给函数进行调用,因此只需除去括号并记住启动线程即可:
Because of the trailing ()
on the target=self.read()
, you're running self.read
in the wrong thread, the current thread — not the new thread you're creating — and passing the return value of the self.read
call as the target
argument of Thread
. Thread
expects to be passed a function to call, so just remove the parentheses and remember to start the thread:
t1=threading.Thread(target=self.read)
t1.start()
print("something")
对于需要参数的目标,可以在threading.Thread
中使用args
和kwargs
参数,也可以使用lambda.例如,要在线程中运行f(a, b, x=c)
,可以使用
For targets that need arguments, you can use the args
and kwargs
arguments to threading.Thread
, or you can use a lambda. For example, to run f(a, b, x=c)
in a thread, you could use
thread = threading.Thread(target=f, args=(a, b), kwargs={'x': c})
或
thread = threading.Thread(target=lambda: f(a, b, x=c))
请注意,如果您选择了lambda,lambda会在使用时查找f
,a
,b
和c
,而不是在定义lambda
时查找,因此您可以如果您在调度线程之前重新分配了这些变量中的任何一个,则可能会得到意外的结果(即使您立即调用start
,这可能会花费很长的时间).
though watch out if you pick the lambda - the lambda will look up f
, a
, b
, and c
at time of use, not when the lambda
is defined, so you may get unexpected results if you reassign any of those variables before the thread is scheduled (which could take arbitrarily long, even if you call start
immediately).
这篇关于线程在调用Thread.start之前开始运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!