gpt4 book ai didi

python - 新线程阻塞主线程

转载 作者:太空狗 更新时间:2023-10-30 00:31:48 25 4
gpt4 key购买 nike

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()。

守护进程没有解决我的问题,因为我的问题是主线程在新线程启动后立即停止,而不是因为主线程执行结束。

最佳答案

如所写,对Thread 构造函数的调用是调用 self.method2 而不是引用它。将 target=self.method2() 替换为 target=self.method2,线程将并行运行。

请注意,根据您的线程执行的操作,CPU 计算可能仍会因 the GIL 而序列化。 .

关于python - 新线程阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com