新线程阻塞主线程

psy*_*tic 6 python multithreading

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 ...
Run Code Online (Sandbox Code Playgroud)

有可能这样做吗?在new_thread.start()主线程等待它完成之后,为什么会发生这种情况?我没有在任何地方提供new_thread.join().

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

use*_*342 13

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

请注意,根据您的线程执行的操作,由于GIL,CPU计算可能仍会被序列化.

  • 谢谢!有时我自己找不到这些愚蠢的错误提示。 (3认同)