python 程式池的兩種不同實現

ponponon發表於2023-05-11

方式一:使用 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)

相關文章