关于python:python-进程池的两种不同实现

33次阅读

共计 713 个字符,预计需要花费 2 分钟才能阅读完成。

形式一:应用 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)

正文完
 0