【问题标题】:new thread blocks main thread新线程阻塞主线程
【发布时间】:2015-06-08 05:46:59
【问题描述】:
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()。

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

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

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

    请注意,根据您的线程所做的事情,由于the GIL,CPU 计算可能仍会被序列化。

    【讨论】:

    • 谢谢!有时我自己也找不到这些愚蠢的错误提示。
    【解决方案2】:

    IIRC,这是因为程序在所有非守护线程完成执行之前不会退出。如果您改用守护线程,它应该可以解决问题。此答案提供了有关守护线程的更多详细信息:

    Daemon Threads Explanation

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 2016-09-25
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多