Python – Non-blocking class in python (detached Thread)

multithreadingnonblockingpython

I'm trying to create a kind of non-blocking class in python, but I'm not sure how.

I'd like a class to be a thread itself, detached from the main thread so other threads can interact with it.

In a little example:

#!/usr/bin/python2.4

import threading
import time

class Sample(threading.Thread):
    def __init__(self):
        super(Sample, self).__init__()
        self.status = 1
        self.stop = False

    def run(self):
        while not(self.stop):
            pass

    def getStatus(self):
        return self.status

    def setStatus(self, status):
        self.status = status

    def test(self):
        while self.status != 0:
            time.sleep(2)

#main
sample = Sample()
sample.start()
sample.test()
sample.setStatus(0)
sample.stop()

What I'd like is having the "sample" instance running as a separate thread (detached from the main one) so, in the example, when the main thread reaches sample.test(), sample (and only "sample") would go to sleep for 2 seconds. In the meanwhile, the main thread would continue its execution and set sample's status to 0. When after the 2 seconds "sample" wakes up it would see the status=0 and exit the while loop.

The problem is that if I do this, the line sample.setStatus(0) is never reached (creating an infinite loop). I have named the threads, and it turns out that by doing this, test() is run by the main thread.

I guess I don't get the threading in python that well…

Thank you in advance

Best Solution

The object's run() method is what executes in a separate thread. When you call sample.test(), that executes in the main thread, so you get your infinite loop.