Skip to content

Instantly share code, notes, and snippets.

@amirasaran
Created October 27, 2016 06:36
Show Gist options
  • Save amirasaran/e91c7253c03518b8f7b7955df0e954bb to your computer and use it in GitHub Desktop.
Save amirasaran/e91c7253c03518b8f7b7955df0e954bb to your computer and use it in GitHub Desktop.
Python threading with callback function (callback function run after thread is finished)
import time
import threading
class BaseThread(threading.Thread):
def __init__(self, callback=None, callback_args=None, *args, **kwargs):
target = kwargs.pop('target')
super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
self.callback = callback
self.method = target
self.callback_args = callback_args
def target_with_callback(self):
self.method()
if self.callback is not None:
self.callback(*self.callback_args)
def my_thread_job():
# do any things here
print "thread start successfully and sleep for 5 seconds"
time.sleep(5)
print "thread ended successfully!"
def cb(param1, param2):
# this is run after your thread end
print "callback function called"
print "{} {}".format(param1, param2)
# example using BaseThread with callback
thread = BaseThread(
name='test',
target=my_thread_job,
callback=cb,
callback_args=("hello", "world")
)
thread.start()
@zzeitlin
Copy link

@pratham2003 If anybody else finds this, it would be something similar to how you pop'd the target :

class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        firstarg = kwargs.pop('first')                # inserted
        secondarg = kwargs.pop('secound')   # inserted
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.firstarg = firstarg                        # inserted
        self.seccondarg = secondarg           # inserted
        self.callback_args = callback_args


    def target_with_callback(self):         
        self.method(self.firstarg, self.secondarg)     # inserted parameters (note: "method" has been defined as "target" which is my_thread_job()
        if self.callback is not None:
            self.callback(*self.callback_args)

def my_thread_job(arg1, arg2):     # inserted parameters
    # do any things here
    print "thread start successfully and sleep for 5 seconds"
    time.sleep(5)
    print(arg1)
    print(arg2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment