Zeeshan Akhter
Zeeshan Akhter

Reputation: 476

Upated class attribute not getting reflected in multiprocessing function

I have a Python 3.6.6 multiprocessing function running on windows

import multiprocessing as mp

class Foo:
    def __new__(cls):
        return None
    name = 'apple'

    @staticmethod
    def worker():
        print(f'Inside worker => {Foo.name}')

    @staticmethod
    def caller():
        for _ in range(3):
            p = mp.Process(target=Foo.worker)
            p.start()
            p.join()


if __name__ == '__main__':
    Foo.name ='ball'
    Foo.caller() # worker prints apple
    Foo.worker() # prints ball

As per my understanding, in the function worker the values of class attribute name should ball but actually it's apple.

I looked for an explanation for this but can't find any. Thanks in advance.

Upvotes: 1

Views: 30

Answers (1)

Selcuk
Selcuk

Reputation: 59258

Your program has 4 processes: 1 main and 3 children. You modify the class attribute in your main process but any newly spawned process will load the class again, using the values in the class definition.

The main difference between threads and processes is shared memory. If you use Threads instead of Processes you will see that it will use the modified class definition:

p = threading.Thread(target=Foo.worker)

Upvotes: 1

Related Questions