新线程阻止主线程 [英] new thread blocks main thread
问题描述
from threading import Thread
class MyClass:
#...
def method2(self):
while True:
try:
hashes = self.target.bssid.replace(':','') + '.pixie'
text = open(hashes).read().splitlines()
except IOError:
time.sleep(5)
continue
# function goes on ...
def method1(self):
new_thread = Thread(target=self.method2())
new_thread.setDaemon(True)
new_thread.start() # Main thread will stop there, wait until method 2
print "Its continues!" # wont show =(
# function goes on ...
有可能这样做吗? 在 new_thread.start()之后,主线程一直等到完成后,为什么会发生这种情况?我没有在任何地方提供new_thread.join().
Is it possible to do like that? After new_thread.start() Main thread waits until its done, why is that happening? i didn't provide new_thread.join() anywhere.
守护进程不能解决我的问题,因为我的问题是主线程在新线程启动后立即停止,而不是因为主线程执行已结束.
Daemon doesn't solve my problem because my problem is that Main thread stops right after new thread start, not because main thread execution is end.
推荐答案
按照编写,对Thread
构造函数的调用是调用 self.method2
而不是引用它.将target=self.method2()
替换为target=self.method2
,线程将并行运行.
As written, the call to the Thread
constructor is invoking self.method2
instead of referring to it. Replace target=self.method2()
with target=self.method2
and the threads will run in parallel.
请注意,由于 GIL,
Note that, depending on what your threads do, CPU computations might still be serialized due to the GIL.
这篇关于新线程阻止主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!