Asynchronous callback is required in many scenarios to avoid blocking. This is a simple example. Multithreading and asynchronization in python are commonly used in the queue and threading modules #! Usrbinenvpython #-... in many scenarios, asynchronous callback is required to avoid blocking. This is a simple example.
Multithreading and asynchronization in python are commonly used in the queue and threading modules.
#! /Usr/bin/env python #-*-coding: UTF-8-*-import loggingimport queueimport threading def func_a (a, B): return a + B def func_ B (): pass def func_c (a, B, c): return a, B, c # asynchronous task queue _ task_queue = queue. queue () def async_call (function, callback, * args, ** kwargs): _ task_queue.put ({'function': function, 'callback': callback, 'args ': args, 'kwargs ': kwargs}) def _ task_queue_consumer (): "asynchronous task queue consumer" while True: try: task = _ task_queue.get () function = task. get ('function') callback = task. get ('callback') args = task. get ('args ') kwargs = task. get ('kwargs ') try: if callback: callback (function (* args, ** kwargs) except T Exception as ex: if callback: callback (ex) finally: _ task_queue.task_done () partition T Exception as ex: logging. warning (ex) def handle_result (result): print (type (result), result) if _ name _ = '_ main _': t = threading. thread (target = _ task_queue_consumer) t. daemon = True t. start () terminate (func_a, handle_result, 1, 2) async_call (func_ B, handle_result) async_call (func_c, handle_result, 1, 2, 3) terminate (func_c, handle_result, 1, 2, 3, 4) _ task_queue.join ()