【问题标题】:使用 concurrent.futures.ProcessPoolExecutor 的运行时错误
【发布时间】:2022-01-20 15:08:26
【问题描述】:

我在 YouTube 上看过很多 concurrent.futures.ProcessPoolExecutor 的基本教程视频。我还看到了 SO here 和 here、GitHub 和 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 代码中进行多处理。

这是我的伪代码:

模块.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

我的类文件 (classObject.py) 没有“主”保护。

我尝试过的事情:

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

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

我使用的是 MacBook Pro(16 英寸,2019 年),处理器 2.3 GHz 8 核 Intel Core i9,操作系统:Big Sur。我认为这并不重要,但如果确实如此,请声明它。

【问题讨论】:

    标签: python-3.x multiprocessing python-multiprocessing concurrent.futures


    【解决方案1】:

    您需要将参数作为可选对象传递,例如列表或元组。 你不需要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()
    

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 2017-07-08
      • 2022-07-13
      • 2022-09-28
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多