Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...

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.

like image 218
psyskeptic Avatar asked Jun 08 '15 05:06

psyskeptic


1 Answers

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.

like image 183
user4815162342 Avatar answered Oct 12 '22 17:10

user4815162342