Python multiprocessing refuses to loop
Question: 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?


Answer: 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"
    

