形式一:应用 multiprocessing 库
from loguru import loggerimport multiprocessingdef start_request(message: str) -> int: try: logger.debug(message) except Exception as error: logger.exception(error)if __name__ == "__main__": pool = multiprocessing.Pool(processes=2) for message in ['haha', 'hehe']: pool.apply_async(start_request, (message,)) pool.close() pool.join()
形式二:应用 concurrent.futures 的 ProcessPoolExecutor
from loguru import loggerimport multiprocessingfrom concurrent.futures import ProcessPoolExecutordef start_request(message: str) -> int: try: logger.debug(message) except Exception as error: logger.exception(error)if __name__ == "__main__": pool = ProcessPoolExecutor( max_workers=2 ) for message in ['haha', 'hehe']: pool.submit(start_request, message) pool.shutdown(wait=True)