线程在调用 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
,当前 线程——而不是你正在创建的新线程——并传递返回值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")
对于需要参数的目标,您可以使用 args
和 kwargs
参数到 threading.Thread
,或者您可以使用 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屋!