【发布时间】:2021-02-21 11:41:16
【问题描述】:
我正在尝试在 Windows 机器上使用线程和多处理的第一个正式 Python 程序。我无法启动这些进程,python 给出了以下消息。问题是,我没有在 main 模块中启动我的线程。线程在类内的单独模块中处理。
编辑:顺便说一下,这段代码在 ubuntu 上运行良好。不完全在 Windows 上
RuntimeError:
Attempt to start a new process before the current process
has finished its bootstrapping phase.
This probably means that you are on Windows 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 a Windows executable.
我的原始代码很长,但我能够在代码的删减版本中重现该错误。它分为两个文件,第一个是主模块,除了导入处理进程/线程和调用方法的模块外,它几乎没有做任何事情。第二个模块是代码的核心所在。
testMain.py:
import parallelTestModule
extractor = parallelTestModule.ParallelExtractor()
extractor.runInParallel(numProcesses=2, numThreads=4)
parallelTestModule.py:
import multiprocessing
from multiprocessing import Process
import threading
class ThreadRunner(threading.Thread):
""" This class represents a single instance of a running thread"""
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print self.name,'\n'
class ProcessRunner:
""" This class represents a single instance of a running process """
def runp(self, pid, numThreads):
mythreads = []
for tid in range(numThreads):
name = "Proc-"+str(pid)+"-Thread-"+str(tid)
th = ThreadRunner(name)
mythreads.append(th)
for i in mythreads:
i.start()
for i in mythreads:
i.join()
class ParallelExtractor:
def runInParallel(self, numProcesses, numThreads):
myprocs = []
prunner = ProcessRunner()
for pid in range(numProcesses):
pr = Process(target=prunner.runp, args=(pid, numThreads))
myprocs.append(pr)
# if __name__ == 'parallelTestModule': #This didnt work
# if __name__ == '__main__': #This obviously doesnt work
# multiprocessing.freeze_support() #added after seeing error to no avail
for i in myprocs:
i.start()
for i in myprocs:
i.join()
【问题讨论】:
-
@doctorlove 我将它作为 python testMain.py 运行
-
当然 - 你需要一个 if name == 'main' 查看答案和文档
-
@NGAlgo 在我调试 pymongo 和多处理问题时,您的脚本对我很有帮助。谢谢!
标签: python windows multiprocessing