python multiprocessing, do the processes share a common variable?
Question: I have this:

    
    
    #!/usr/bin/env python
    
    import multiprocessing
    
    class MultiprocessingTest(object):
    
        def __init__(self):
            self.cmd = ''
    
        def for_process_A(self):
            self.cmd = "AA"
            print "%s executing and cmd is %s" % (multiprocessing.current_process().name, self.cmd)
    
    
        def for_process_B(self):
            self.cmd = "BB"
            print "%s executing and cmd is %s" % (multiprocessing.current_process().name, self.cmd)
    
    
    if __name__ == '__main__':
    
        obj =   MultiprocessingTest()
    
        process_A = multiprocessing.Process(target=obj.for_process_A, name='process_A')
        process_B = multiprocessing.Process(target=obj.for_process_B, name='process_B')
    
        process_A.start()
        process_B.start()
    
    
        process_A.join()
        process_B.join()
    

Question:

Do the two processes share the variable `cmd`?

Do both processes have a separate class `MultiprocessingTest` definition and
work off of that?

Independent copies of which data exists in the two processes?

I am trying to understand from a theoretical standpoint what is actually
happening here. Can you please comment on that?

Test Run o/p:

    
    
    $ ./commonvar.py 
    
    process_A executing and cmd is AA
    
    process_B executing and cmd is BB
    


Answer: Processes don't share data. Each process is a separate container with
following resources, generally speaking:

  * Code to execute
  * Stack
  * Processor time

Processes interact with outside world through Pipes.

So to answer your questions:

  * Processes will not share `cmd` variable.
  * Processes will have separate copies of the class code.
  * All the program data will be independent.

Further Explanation:

Behind the scenes, [fork system
call](http://en.wikipedia.org/wiki/Fork_%28system_call%29) is used to create a
process (assuming you are using *nix). Processes are heavier compared to
threads because of the overhead involved in [switching the
conext](http://en.wikipedia.org/wiki/Context_switch).

