Python2.7中重新启动时的多处理进程错误

2024-06-11 05:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

你认为下面的代码有什么问题?在

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()  

如果我执行以下操作:

  • 初始化进程
  • 启动流程->;(流程立即结束)
  • 验证进程是否已完成并执行联接()
  • 重新启动进程

这是测试的输出:

^{pr2}$

我得到这个错误:

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

可能是过程中不能多次启动后完成和终止相同? 如果是这样的话,每次你想开始新工作时,我都必须创建一个新流程吗?(似乎很奇怪)
但最重要的是,它只发生在我身上?因为在网上我找不到任何争论。
我确实遗漏了一些东西,但我不知道是什么。。。在


Tags: runselfif进程initismaindef
1条回答
网友
1楼 · 发布于 2024-06-11 05:58:20

来自multiprocessing文档。在

start()

Start the process’s activity.

This must be called at most once per process object. It arranges for the object’s run() method to be invoked in a separate process.

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

相关问题 更多 >