简体   繁体   English

Python多处理-进程终止(无法两次启动进程)

[英]Python Multiprocessing - Process Termination (cannot start a process twice)

Can anyone tell me why the following code gives the error "cannot start a process twice"? 谁能告诉我下面的代码为什么给出错误“无法两次启动进程”? By my reckoning, p1 and p2 should already have been force-closed by the p.terminate() command 据我估计,p1和p2应该已经被p.terminate()命令强制关闭了。

EDIT: Have added in some more code to give context - wanted to come up with a simple example but left out the while loops 编辑:添加了更多的代码来提供上下文-想拿出一个简单的示例,但省略了while循环

import time
import os
from multiprocessing import Process
import datetime

def a():
    print ("a starting")
    time.sleep(30)
    print ("a ending")

def b():
    print ("b starting")
    time.sleep(30)
    print ("b ending")

morning = list(range(7,10))
lunch = list(range(11,14))
evening = list(range(17,21))
active = morning + lunch + evening

if __name__=='__main__':
    p1 = Process(target = a)
    p2 = Process(target = b)
    while True:
        while (datetime.datetime.now().time().hour) in active:
            p1.start()
            p2.start() 
            time.sleep(5)
            p1.terminate()
            p2.terminate()
            time.sleep(5)
        else:
            print ("Outside hours, waiting 30 mins before retry")
            time.sleep(1800)

It says you cannot start a process twice. 它说您不能两次启动一个进程。 That is exactly what you're doing when you call p1.start() and p2.start() again after the terminates. 这就是终止后再次调用p1.start()p2.start()时所做的事情。 Try recreating them like you did at the beginning. 尝试像开始时那样重新创建它们。

p1.terminate()
p2.terminate()
time.sleep(5)
p1 = Process(target = a)
p2 = Process(target = b)
p1.start()
p2.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM