[FIXED] Python instance counter in ProcessPool

Issue

I'm having trouble finding the correct way to implement the following: I have a class in Python3 for which I keep an instance counter. Using a concurrent.futures.ProcessPoolExecutor, I submit several tasks that make use of this class. I assumed that since the tasks ran in separate processes there would be no shared state between them, but it would seem I was wrong as this instance counter is shared among them. The following code exemplifies what I mean:

import concurrent.futures

class A:
     counter = 0
     def __init__(self):
         A.counter += 1
         self.id = A.counter
     def hello(self):
         return f'Hello from node{self.id}'

def start():
     instance = A()
     return instance.hello()

results = []
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
     for i in range(4):
         f = executor.submit(start)
         results.append(f)

for r in results:
     print(r.result())


The output from the above is:

Hello from node1
Hello from node2
Hello from node1
Hello from node1

The issue is not the race condition when accessing the counter, my issue is that the variable is even shared at all when I was expecting it to be private per process (e.g. start at 0 for each worker). What would be a pythonic way to achieve this?

Thanks in advance.


Solution

Here it would seem you found that tasks are not always evenly distributed between workers within a processing pool, and one of the workers managed to complete 2 "tasks" while one (of the 4) got none. In each worker the A class is defined either by copying the memory space from the time at which fork is called (*nix) or from importing the main file (Windows and MacOS). The class attribute counter behaves like a global variable, because it was not defined as an instance attribute, so any worker getting multiple tasks will see that value incremented each time. While it is possible to avoid this by limiting workers to only completing one task each before they're terminated and re-started, it's generally good practice to avoid global state in general. maxtasksperchild is much more frequently used to clean up instances where child processes may for various reasons not release memory or file handles over time to prevent leaks.

As you have stated in the comments, a long running task reduces the relative impact of the overhead of re-starting the process each task, however if you are using any of the functions that map a function over an iterable, and accept a chunksize argument, this approach may break. A "task" isn't specifically one iteration of the map, but may be several at once (to reduce overhead of transferring the arguments and results). This example should demonstrate a pool with maxtasksperchild=1, where each child ends up calling start() 4 times:

from multiprocessing import Pool
class A:
     counter = 0
     def __init__(self):
         A.counter += 1
         self.id = A.counter
     def hello(self):
         return f'Hello from node{self.id}'

def start(_):
     instance = A()
     print( instance.hello())

if __name__ == "__main__":
    with Pool(4, maxtasksperchild=1) as p:
        p.map(start, range(16), chunksize=4)


Answered By - Aaron
Answer Checked By - Willingham (Python.Easybugfix Volunteer)

Related Posts

Post a Comment