multiprocessing pool AttributeError: Can't get attribute 'func'

ponponon發表於2022-06-15

python 使用 multiprocessing 構建程式池 報錯:AttributeError: Can't get attribute 'func'

正確的程式池使用方式:

import requests
from loggers import logger
import multiprocessing


def func():
    try:
        for i in range(1):
            response = requests.get(
                'http://localhost:63000/')
            print(response.status_code, response.text)
    except Exception as error:
        logger.exception(error)


if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=56)
    for i in range(100000):
        pool.apply_async(func)

錯誤的程式池使用方式:

import requests
from loggers import logger
import multiprocessing

pool = multiprocessing.Pool(processes=56)


def func():
    try:
        for i in range(1):
            response = requests.get(
                'http://localhost:63000/')
            print(response.status_code, response.text)
    except Exception as error:
        logger.exception(error)


if __name__ == "__main__":

    for i in range(100000):
        pool.apply_async(func)

所以,必須要把 pool 這個全域性變數放到 if __name__ == "__main__": 中去

相關文章