0

I've recently discovered Multiprocessing for Python, so I'm playing around with it a little bit and I ran into a wall.

This is the script I'm working with:

import multiprocessing, time

def p_def():
        print "running p"
        time.sleep(5)

def v_def():
        print "running v"
        time.sleep(5)

p = multiprocessing.Process(target=p_def)
v = multiprocessing.Process(target=v_def)

while True:
        time.sleep(0.25)
        p.start()
        while p.is_alive() == True:
                time.sleep(0.5)
                print "waiting for it to finish"

All works well when I run the code, it starts up the p_def but when it finishes and wants to run it again, it runs into a snag and outputs me this error:

running p
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
waiting for it to finish
Traceback (most recent call last):
  File "proc.py", line 19, in <module>
    p.start()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 120, in start
    assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

This seems a little odd to me. My understanding says it should be able to run it again, although, what I see online is people saying it cannot run the same thing twice.

What's the truth and how can I make it run twice?

1
  • Not directly related to the question, but instead of busy-waiting for the process to exit, you can (and probably should) use the p.join() function. Commented Apr 15, 2016 at 9:50

1 Answer 1

2

You need to recreate the object p, a process can be start only one time. (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.start)

import multiprocessing, time

def p_def():
        print "running p"
        time.sleep(5)

def v_def():
        print "running v"
        time.sleep(5)

v = multiprocessing.Process(target=v_def)

while True:
        time.sleep(0.25)
        p = multiprocessing.Process(target=p_def)
        p.start()
        while p.is_alive() == True:
                time.sleep(0.5)
                print "waiting for it to finish"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.