Mots clés : pythondjangomultithreadingdecoratorpython-multithreadingpython
100
def start_new_thread(function): def decorator(*args, **kwargs): t = Thread(target = function, args=args, kwargs=kwargs) t.daemon = True t.start() return decorator
@start_new_thread def foo(): #do stuff
from django.db import connection @postpone def foo(): #do stuff connection.close()
82
# in my_utils.py from concurrent.futures import ThreadPoolExecutor MAX_THREADS = 10 def run_thread_pool(): """ Note that this is not a normal function, but a coroutine. All jobs are enqueued first before executed and there can be no more than 10 threads that run at any time point. """ with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: while True: func, args, kwargs = yield executor.submit(func, *args, **kwargs) pool_wrapper = run_thread_pool() # Advance the coroutine to the first yield (priming) next(pool_wrapper)
from my_utils import pool_wrapper def job(*args, **kwargs): # do something def handle(request): # make args and kwargs pool_wrapper.send((job, args, kwargs)) # return a response