Christopher Pavlou
Christopher Pavlou

Reputation: 33

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

EDIT: Have added in some more code to give context - wanted to come up with a simple example but left out the while loops

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)

Upvotes: 3

Views: 5956

Answers (1)

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

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

Upvotes: 5

Related Questions