在Python 2.7中重新启动时的多处理过程错误

时间:2015-10-22 19:35:08

标签: python python-2.7 process multiprocessing python-multiprocessing

您认为以下代码有什么问题?

from multiprocessing import Process as multicore  

class tbe_worker(multicore):  
    def __init__(self):  
        multicore.__init__(self)  
        print "init tbe_worker"  

    def run(self):  
        print "run tbe_worker"  

class Main:  
    def __init__(self):  
        self.w_tbe = tbe_worker()  
        print self.w_tbe  
        print "create w_tbe instance"  

    def startelab(self):  
        print "start thread"  
        print "alive:", self.w_tbe.is_alive()  
        print self.w_tbe  
        self.w_tbe.start()  
        print "after start"  
        print self.w_tbe  

    def stopelab(self):  
        print "alive:", self.w_tbe.is_alive()  
        print "exitcode:", self.w_tbe.exitcode  
        if self.w_tbe.is_alive():  
            print "alive:", self.w_tbe.is_alive()  
            self.w_tbe.terminate()  
            print "alive:", self.w_tbe.is_alive()  
        self.w_tbe.join()  
        print "alive:", self.w_tbe.is_alive()  
        print self.w_tbe  

    def run(self):  
        print "before main run"            
        while True:  
            x = raw_input()  
            if x == "v":  
                self.startelab()  
            else:  
                self.stopelab()  
        print "after main run"  

if __name__ == '__main__':  
    Main().run()  

如果我执行以下操作:

  • 初始化流程
  • 启动流程 - > (流程立即结束)
  • 验证该过程已完成并执行join()
  • 重启流程

这是测试的输出:

init tbe_worker
<tbe_worker(tbe_worker-1, initial)>
create w_tbe instance
before main run
v
start thread
alive: False
<tbe_worker(tbe_worker-1, initial)>
after start
<tbe_worker(tbe_worker-1, started)>
run tbe_worker
c
alive: False
exitcode: 0
alive: False
<tbe_worker(tbe_worker-1, stopped)>
v
start thread
alive: False
<tbe_worker(tbe_worker-1, stopped)>

我收到此错误:

File "C:/Program Files/Python27x64/lib/multiprocessing/process.py", line 120,
in start
    assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice
Press any key to continue . . .

可能是在完成并终止该过程后,该过程不能多次启动? 如果是这样,每次要开始新工作时我是否必须创建新流程? (这似乎很奇怪)
但最重要的是,它只发生在我身上?因为在网上我没有发现任何争论 肯定有一些我不知道的东西,但我无法弄清楚是什么......

1 个答案:

答案 0 :(得分:1)

来自multiprocessing文档。

  

开始()

     

启动流程的活动。

     

每个进程对象最多只能调用一次。它安排在一个单独的进程中调用对象的run()方法。

如果要再次启动目标函数,则需要创建一个新的Process对象。流程对象是唯一的,它们的生命周期本身就与流程绑定。