new thread blocks main thread

11.1k Views Asked by At
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 ...

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

Note that, depending on what your threads do, CPU computations might still be serialized due to the GIL.

0
On

IIRC, this is because the program doesn't exit until all non-daemon threads have finished execution. If you use a daemon thread instead, it should fix the issue. This answer gives more details on daemon threads:

Daemon Threads Explanation