How to control a long running object in Python?

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Posts: 42
Joined: Thu Oct 08, 2015 4:56 am UTC

How to control a long running object in Python?

Postby jacques01 » Fri Sep 23, 2016 10:47 pm UTC

Update: It looks like the answer was simply to run the object's method in a thread. Then I can edit the object outside the thread and get the behavior I desired. However I'd appreciate any perls of wisdom when using Python's threading for this kind of purpose.

I have an custom object which has a long running function. I want to be able to tell the object to stop running the method without killing it, e.g. so that it waits again for a signal to resume its work.

Code: Select all

class Foo(object):
    def __init__(self):
        self.msg = ''

    def do(self):
        for x in xrange(0, 100000):
            if self.msg == 'stop':
                print 'Foo received stop.  Terminating'
            print 'Current x: {}'.format(x)
 FOO = Foo()
 def stopFoo():
   FOO.msg = 'stop'

Now, somewhere down the line, someone sends an HTTP request telling FOO to run

// got called somewhere

Now, someone wants to tell FOO to stop running. In another HTTP request, they do this:

//FOO.msg = 'stop'

However, I observe that continues to execute! And the FOO.msg = 'stop' keeps blocking.

How can I change FOO's field while its running, such that it will stop in a controlled manner?

Return to “Coding”

Who is online

Users browsing this forum: No registered users and 46 guests