What is wrong with this Python Multiprocessing Code?
Question: I am trying to create some multiprocessing code for my project. I have created
a snippet of the things that I want to do. However its not working as per my
expectations. Can you please let me know what is wrong with this.

    
    
    from multiprocessing import Process, Pipe
    import time
    
    class A:
          def __init__(self,rpipe,spipe):
              print "In the function fun()"
    
          def run(self):
               print"in run method"
               time.sleep(5)
               message = rpipe.recv()
               message = str(message).swapcase()
               spipe.send(message)
    
     workers = []
     my_pipe_1 = Pipe(False)
     my_pipe_2 = Pipe(False)
     proc_handle = Process(target = A, args=(my_pipe_1[0], my_pipe_2[1],))
     workers.append(proc_handle)
     proc_handle.run()
     my_pipe_1[1].send("hello")
     message = my_pipe_2[0].recv()
     print message
     print "Back in the main function now"
    

The trace back displayed when i press ctrl-c:

    
    
     ^CTraceback (most recent call last):
     File "sim.py", line 22, in <module>
     message = my_pipe_2[0].recv()
     KeyboardInterrupt
    

When I run this above code, the main process does not continue after calling
"proc_handle.run". Why is this?


Answer: You've misunderstood how to use `Process`. You're creating a `Process` object,
and passing it a class as `target`, but `target` is meant to be passed a
callable (usually a function) that `Process.run` then executes. So in your
case it's just instantiating `A` inside `Process.run`, and that's it.

You should instead make your `A` class a `Process` subclass, and just
instantiate it directly:

    
    
    #!/usr/bin/python
    
    from multiprocessing import Process, Pipe
    import time
    
    class A(Process):
          def __init__(self,rpipe,spipe):
              print "In the function fun()"
              super(A, self).__init__()
              self.rpipe = rpipe
              self.spipe = spipe
    
          def run(self):
               print"in run method"
               time.sleep(5)
               message = self.rpipe.recv()
               message = str(message).swapcase()
               self.spipe.send(message)
    
    if __name__ == "__main__":    
        workers = []
        my_pipe_1 = Pipe(False)
        my_pipe_2 = Pipe(False)
        proc_handle = A(my_pipe_1[0], my_pipe_2[1])
        workers.append(proc_handle)
        proc_handle.start()
        my_pipe_1[1].send("hello")
        message = my_pipe_2[0].recv()
        print message
        print "Back in the main function now"
    

mgilson was right, though. You should call `start()`, not `run()`, to make
`A.run` execute in a child process.

With these changes, the program works fine for me:

    
    
    dan@dantop:~> ./mult.py 
    In the function fun()
    in run method
    HELLO
    Back in the main function now
    

