使用 concurrent.futures.ProcessPoolExecutor 时出现运行时错误

Runtime error using concurrent.futures.ProcessPoolExecutor

我看过很多 concurrent.futures.ProcessPoolExecutor 的基础教程的 YouTube 视频。我也在 SO here and here, GitHub and GitHubMemory 中看到过帖子,但没有运气。

问题: 我收到以下运行时错误:

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

我承认,我不完全理解这个错误,因为这是我第一次尝试在我的 python 代码中进行多处理。

这是我的伪代码:

module.py

import xyz
from multiprocessing import freeze_support

def abc():
  return x

def main():
  xyz
  qwerty

if __name__ == "__main__":
  freeze_support()
  obj = Object()
  main()

classObject.py

import abcd

class Object(object):

  def __init__(self):
    asdf
    cvbn
    with concurrent.futures.ProcessPoolExecutor(max_workers=2) as  executor:
      executor.map(self.function_for_multiprocess, var1, var2)
      # ****The error points at the code above.** 

  def function_for_multiprocess(var1, var2):
    doSomething1
    doSomething2

    self.variable = something

我的 class 文件 (classObject.py) 没有“主要”守卫。

我尝试过的事情:

  1. 尝试在 classObject.py 中添加 if __name__ == "__main__":freeze_support 并重命名 __init__() to main()`
  2. 在执行上述操作时,从 module.py
  3. 中删除了 freeze_support

我还没有找到与上面提供的 link 不同的解决方案。任何见解将不胜感激!

我使用的是 MacBook Pro(16 英寸,2019 年),处理器 2.3 GHz 8 核英特尔酷睿 i9,OS:Big Sur。我认为这不重要,但如果重要,就声明它。

您需要将参数作为可腌制对象传递,例如列表或元组。 而且你不需要 freeze_support() 只需更改 executor.map(self.function_for_multiprocess, var1, var2)executor.map(self.function_for_multiprocess, (var1, var2))

from multiprocessing import freeze_support
import concurrent.futures

class Object(object):

    def __init__(self, var1=1, var2=2):
        with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
            executor.map(self.function_for_multiprocess, (var1, var2))

    def function_for_multiprocess(var1, var2):
        print('var1:', var1)
        print('var2:', var2)

def abc(x):
    return x

def main():
    print('abc:', abc(200))

if __name__ == "__main__":
    #freeze_support()
    obj = Object()
    main()