0

I have a set of objects which do some computing and plotting - they run in threads. After all threads join(), I want to access class attributes of the objects from my main function.

This is small example

import multiprocessing
import numpy as np

class Foo(object):

    def __init__(self, i):
        self.i = i

    def run(self):
        self.l = np.empty([1024])
        self.l.fill(self.i)

foos = []
threads = []
for i in range(8):
    foo = Foo(i)
    foos.append(foo)
    thread = multiprocessing.Process(target=foo.run)
    thread.start()

[thread.join() for thread in threads]

print [foo.l for foo in foos] # AttributeError: 'Foo' object has no attribute 'l'

I saw this post: how to get the return value from a thread in python? But it requires the method to have a return value.

Community
  • 1
  • 1
ppasler
  • 3,579
  • 5
  • 31
  • 51
  • 1
    You have two choices. Either use a queuing system or make your class a Thread and you will be able to call get methods with your threads. – iFlo Jan 27 '17 at 13:18

1 Answers1

0

As @iFlo suggested I tried a Queue base solution.

I had to use threading instead of multithreading, as adding a Queue to Foo cause an Error

TypeError: can't pickle thread.lock objects

However this did the trick:

import multiprocessing
import numpy as np
from Queue import Queue

class Foo(object):

    def __init__(self, i, queue):
        self.i = i
        self.queue = queue

    def run(self):
        l = np.empty([1024])
        l.fill(self.i)
        queue.put(l)

threads = []
queue = Queue()
for i in range(8):
    foo = Foo(i, queue)
    thread = multiprocessing.Process(target=foo.run)
    thread.start()

[thread.join() for thread in threads]

print list(queue.queue)
ppasler
  • 3,579
  • 5
  • 31
  • 51