Python uses multiprocessing to build a process pool and reports an error: AttributeError: Can't get attribute 'func'

The correct way to use the process pool:

 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)

Wrong process pool usage:

 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)

Therefore, the global variable pool must be placed in if __name__ == "__main__":


universe_king
3.4k 声望680 粉丝