方式一:使用 multiprocessing 库

from loguru import logger
import multiprocessing


def 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 logger
import multiprocessing
from concurrent.futures import ProcessPoolExecutor


def 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)

universe_king
3.4k 声望680 粉丝