thread starts running before calling Thread.start

怎甘沉沦 提交于 2019-11-26 11:54:14
user634175

You're passing the result of self.read to 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"

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})

or

thread = threading.Thread(target=lambda: f(a, b, x=c))

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!