Skip to content

Instantly share code, notes, and snippets.

@awesomebytes
Last active February 7, 2024 11:51
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save awesomebytes/0483e65e0884f05fb95e314c4f2b3db8 to your computer and use it in GitHub Desktop.
Save awesomebytes/0483e65e0884f05fb95e314c4f2b3db8 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
@Ahmed7fathi
Copy link

Ahmed7fathi commented Jun 15, 2019

it doesn't work if your threaded function in another file and you imported it.
for example:

A.py

from time import sleep
from threading import Thread

def threaded(fn):

def wrapper(*args, **kwargs):
    thread = Thread(target=fn, args=args, kwargs=kwargs)
    thread.start()
    return thread
return wrapper

@threaded
def p(x):
r = 0
for i in range(1, 6):
r = i*x
print(r)
sleep(1)
return "final result {}".format(str(r))

B.py

from A import p

print(p(2))

i need that returned value from p function the code doesn't reach that far

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