zoukankan      html  css  js  c++  java
  • The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable

     1 from multiprocessing import Pool
     2 import os, time, random
     3 
     4 
     5 def worker(msg):
     6     t_start = time.time()   # 获取开始时间
     7     print("%s开始执行,进程号为%d" % (msg, os.getpid()))
     8     # random.random()随机生成0~1之间的浮点数
     9     time.sleep(random.random()*2)
    10     t_stop = time.time()   # 获取执行结束时间
    11     print(msg, "执行完毕,耗时%.2f" % (t_stop-t_start))
    12 
    13 
    14 po = Pool(3)   # 定义一个进程池,最大进程数是3
    15 for i in range(0, 10):
    16     po.apply_async(worker, (i,))
    17 
    18 print("___start___")
    19 po.close()
    20 po.join()
    21 print("___end___")

    运行如上代码时会报以下错误信息:

    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.

    从错误信息可以看出进程池相关代码应该放在if __name__ == '__main__'下面,那么可以将进程池运行相关代码放在main函数下面,代码修改如下:

     1 from multiprocessing import Pool
     2 import os, time, random
     3 
     4 
     5 def worker(msg):
     6     t_start = time.time()   # 获取开始时间
     7     print("%s开始执行,进程号为%d" % (msg, os.getpid()))
     8     # random.random()随机生成0~1之间的浮点数
     9     time.sleep(random.random()*2)
    10     t_stop = time.time()   # 获取执行结束时间
    11     print(msg, "执行完毕,耗时%.2f" % (t_stop-t_start))
    12 
    13 
    14 def main():
    15     # 定义一个进程池,最大进程数是3
    16     po = Pool(3)
    17     for i in range(0, 10):
    18         po.apply_async(worker, (i,))
    19 
    20     print("___start___")
    21     po.close()
    22     po.join()
    23     print("___end___")
    24 
    25 
    26 if __name__ == '__main__':
    27     main()
  • 相关阅读:
    关于 Unity WebGL 的探索(二)
    关于 Unity WebGL 的探索(一)
    Ghostscript 中 ps2pdf 命令在 windows msys 下的运行错误问题。
    编译 Windows 版本的 Unity Mono(2017-03-12 20:59)
    Windows 下使用 mingw+msys 交叉编译 Android Unity Mono
    关于 UGUI 字体花屏或乱码。
    从 NavMesh 网格寻路回归到 Grid 网格寻路。
    Unity光照图UV显示
    2DPlatformer-SLua 编辑器 UI 美化
    SnapDragon Profiler 学习
  • 原文地址:https://www.cnblogs.com/zzmx0/p/12663478.html
Copyright © 2011-2022 走看看