Call a function when a thread exits

  • Thread starter Giampaolo Rodola'
  • Start date
G

Giampaolo Rodola'

Hi,
I'm searching for a smooth way to call a certain function when a
thread has finished its job.
I guess I can keep calling isAlive() in a loop and call my function
when it returns False but it's not very elegant.
Actually I'm a bit surprised it doesn't exists an "atexit" function.
Something like:

import threading, time

def myfun():
time.sleep(1)
print "hello"

def cleanup():
print "thread finished, starting cleanup operations..."

t = threading.Thread(target=myfun)
t.atexit(target=cleanup)
t.start()


Is there a reason why there's no such thing in the threading module?


--- Giampaolo
http://code.google.com/p/pyftpdlib/
 
C

Carl Banks

Hi,
I'm searching for a smooth way to call a certain function when a
thread has finished its job.
I guess I can keep calling isAlive() in a loop and call my function
when it returns False but it's not very elegant.
Actually I'm a bit surprised it doesn't exists an "atexit" function.
Something like:

import threading, time

def myfun():
    time.sleep(1)
    print "hello"

def cleanup():
    print "thread finished, starting cleanup operations..."

t = threading.Thread(target=myfun)
t.atexit(target=cleanup)
t.start()

Is there a reason why there's no such thing in the threading module?

You can define your target function to clean up on exit. Using your
definitions of myfun and cleanup,

def mycleanfun():
try:
myfun()
finally:
cleanup()

t = threading.Thread(target=mycleanfun)
t.start()


Carl Banks
 
G

Giampaolo Rodola'

You can define your target function to clean up on exit.  Using your
definitions of myfun and cleanup,

def mycleanfun():
    try:
        myfun()
    finally:
        cleanup()

t = threading.Thread(target=mycleanfun)
t.start()

Carl Banks

Yes, I know. I was wondering if it could be a good idea proposing
something like an atexit() function to be included in threading
module.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top