我有一组对象进行计算和绘图 - 它们在线程中运行。
在所有线程join()
之后,我想从我的main函数访问对象的类属性。
这是一个小例子
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'
我看过这篇文章:how to get the return value from a thread in python? 但它需要该方法具有返回值。
答案 0 :(得分:0)
正如@iFlo建议我尝试了一个Queue基础解决方案。
我必须使用threading
代替multithreading
,因为向Queue
添加Foo
会导致错误
TypeError:不能挑选thread.lock对象
然而这就是诀窍:
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)