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
it doesn't work if your threaded function in another file and you imported it.
for example:
A.py
B.py
i need that returned value from p function the code doesn't reach that far