0

Code:

import multiprocessing
import multiprocessing.managers

class A:
    name = "A name"
    arr_b = []
    def __init__(self, num):
        for i in range(5):
            self.arr_b.append(B())

class B:
    name = "B name"
    def __init__(self):
        pass

def func(num):
    return A(num)
        
if __name__ == '__main__':
    pool = multiprocessing.Pool()
    result = pool.map(func, range(5))
    for res in result:
        print(res.name)
        print(res.arr_b)

Result:

A name
[]
A name
[]
A name
[]
A name
[]
A name
[]

How i can share array of B class objects correctly? I tried to used Manager and BaseManager, but it allows me to use created in main object. But i need to create object in func and return it into main.

Artem
  • 21
  • 2
  • 1
    What are you trying to do with your func? You are appending to retval and then not using it. Do you intend to return something or are you just wanting to change the underlying class? – chsws May 25 '21 at 14:16
  • yeah, i return it from func – Artem May 25 '21 at 14:19
  • I'm wondering whether it's worth posting your parsing question as well. It seems strange to me that you would want a class attribute of A to be updated through so many calls in the `__init__`. I think this behaviour could possibly cause trouble outside of the problems of multiprocessing (here it makes it very difficult). – chsws May 25 '21 at 14:37
  • @chsws In my case these calls not in __init__. Code at question is a simple example. The problem in using pool.map and trying to return classes, created in another processes. So my question how to resolve this problem? Question not about how much calls in __init__ etc. But thank you for answers) – Artem May 25 '21 at 14:46
  • [This looks useful.](https://stackoverflow.com/questions/3671666/sharing-a-complex-object-between-processes) Very similar question. – chsws May 25 '21 at 15:11
  • @chsws yes, very similar, but one problem, i can create class only in func - not in main. In this question class created in main, then share in func, changing there and in main it changed, but i need to create in func and RETURN in main – Artem May 25 '21 at 15:21
  • I'm stumped. I don't know your exact problem but I would look at reworking your original issue to use standard objects, such as Queue, if possible. good luck. – chsws May 25 '21 at 15:26

0 Answers0