Terminating a function

A

Astan Chee

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?
Thanks
 
D

Diez B. Roggisch

Astan said:
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
 
I

Ian Leitch

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Astan said:
I was thinking of threads but I just simply want to terminate a (global)
function after it has been running for more than 5 minutes regardless of
state.
I was assuming I needed threads because it can calculate time elapsed
(that and im rather inexperienced with threads)
Thanks again for your help!

You can use a thread to do the timing and send an interrupt when the
time is up:

#!/usr/bin/python

import thread
import threading
from time import sleep

def timer_thread():

sleep(10)
thread.interrupt_main()

def my_func():

try:

while 1:

sleep(2)
print "Hello"

except KeyboardInterrupt:

return

my_thread = threading.Thread(target=timer_thread)
my_thread.start()

my_func()

print "Done."
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFD9hxcefZ4eWAXRGIRAnwIAKCH/pH7dyzjk1rsfvFKzrA48GgeEACfdNx6
QmsqAruOESUe2bzPTh/nsE8=
=LvT6
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top