Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ahmed7fathi/7a549c11c9c154b3f9d99344802ca65d to your computer and use it in GitHub Desktop.
Save Ahmed7fathi/7a549c11c9c154b3f9d99344802ca65d to your computer and use it in GitHub Desktop.
Make a function or method threaded in python with a decorator

How to make a python function or class method threaded

From this stack overflow question I got this great snippet.

# Threaded function snippet
def threaded(fn):
    """To use as decorator to make a function call threaded.
    Needs import
    from threading import Thread"""
    def wrapper(*args, **kwargs):
        thread = Thread(target=fn, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return wrapper

Remember that as wikibooks says in Python:

Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time. In that case, you probably want to look into parallel programming.

How to give it a callback

(Untested)

# Threaded function snippet returning a callback when the function has finished
def threaded(fn, callback_func):
    """To use as decorator to make a function call threaded.
    It will call the callback_func when the function returns.
    Needs import
    from threading import Thread"""
    def wrapper(*args, **kwargs):
        def do_callback():
            callback_func(fn(args, kwargs))
        thread = Thread(target=do_callback)
        thread.start()
        return thread
    return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment