views:

54

answers:

2

Hello everyone...

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

+1  A: 

Perhaps something like this?

import threading
import time

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

    def run(self):
        while not(self.stop):
            print('hi')
            time.sleep(.1)

    def test(self):
        print('testing...')
        time.sleep(2)

#main
sample = Sample()
sample.start()      # Initiates second thread which calls sample.run()
sample.test()       # Main thread calls sample.test
sample.stop=True    # Main thread sets sample.stop
sample.join()       # Main thread waits for second thread to finish
unutbu
I guess that may work, but I'd like to have something more "elegant"... I guess I have to change the structure... a lot.Thank you!
BorrajaX
+3  A: 

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.

Sancho
Oh, sh**t... I see... Then I have to change the way I was thinking... Thank you!
BorrajaX