Terminating a function

Diez B. Roggisch deets at nospam.web.de
Fri Feb 17 06:58:09 EST 2006


Astan Chee wrote:

> Hi,
> Im rather new to threads in python but Im trying to terminate a function
> call (or the execution of the function) after a certain period of time
> has passed.
> Do i need to use threads with this? if i do, how do i go about doing it?

Yes and no. As you didn't tell us muc about your actual problem, threads
might be what you need. But you _can't_ just stop a thread - however,
depending on what you do, you can for example regularly check for a flag
inside your function and then  terminate:

class Foo(threading.Thread):
   def __init__(self):
      super(Foo, self).__init__()
      self.setDaemon(True)
      self.interrupted = False

   def run(self):
       while not self.interrupted:
           do_some_work_but_make_sure_to_come_back_regularly()


f = Foo()
f.start()

time.sleep(10)
f.interrupted = True

Diez



More information about the Python-list mailing list