multiprocessing进程开发RuntimeError

windows环境下multiprocessing报如下异常信息:

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__":

代码如下:

import multiprocessing as mp
import os
import time

def th1():
    print("this is th1,the time is {0}".format(time.ctime()))
    #getppid获取父进程ID, getpid获取当前进程ID
    print("th1",os.getppid(), "---", os.getpid())

def setproc():
    p1 = mp.Process(target = th1)
    p1.start()
    print("main", os.getppid(), "---", os.getpid())
    
if __name__ == "__main__":
    #p1 = mp.Process(target = th1)
    #p1.start()

    setproc()
    print("main end")

 

 

 

posted @ 2019-01-21 15:18  雨行渡  阅读(509)  评论(0编辑  收藏  举报