首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用多处理从类内的函数返回值

使用多处理从类内的函数返回值
EN

Stack Overflow用户
提问于 2021-01-07 09:48:38
回答 1查看 55关注 0票数 0

我有下面的代码,我想在并行处理完成后如何获得返回值。我不喜欢对getdata函数做任何更改。

代码语言:javascript
复制
from multiprocessing import Process

class Calculation(object):
    def __init__(self, a, b, c):
        self.A, self.B, self.C= a, b, c
        
    def getdata(self):
        self.Product = self.A * self.B
        self.Subtract = self.C - self.B
        self.Addition = self.A + self.B + self.C
        return self.Product, self.Subtract, self.Addition
    

def foo():
    EXTERNAL_C=[10, 20, 30, 40, 50, 20, 40]
    c = [Calculation(a=4, b=5, c=n) for n in EXTERNAL_C]
    return c
    
K = []
for M in foo():
    p = Process(target=M.getdata)
    p.start()
    K.append(p)
for process in K:
    process.join()
print(K)

输出:

代码语言:javascript
复制
[<Process(Process-8, stopped[1])>, <Process(Process-9, stopped[1])>, <Process(Process-10, stopped[1])>, <Process(Process-11, stopped[1])>, <Process(Process-12, stopped[1])>, <Process(Process-13, stopped[1])>, <Process(Process-14, stopped[1])>]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-07 10:22:54

您在主进程中创建的Calculation对象被复制到生成的进程中,因此存在没有办法提取他们的状态或获得getdata的返回值,而不进行显式操作。

您可以使用multiprocessing.Queue来存储结果,如下所示

代码语言:javascript
复制
from multiprocessing import Process, Queue


class Calculation(object):
    def __init__(self, a, b, c):
        self.A, self.B, self.C = a, b, c

    def getdata(self, id, queue):
        self.Product = self.A * self.B
        self.Subtract = self.C - self.B
        self.Addition = self.A + self.B + self.C
        queue.put(
            {
                "id": id,
                "Product": self.Product,
                "Subtract": self.Subtract,
                "Addition": self.Addition,
            }
        )


def foo():
    EXTERNAL_C = [10, 20, 30, 40, 50, 20, 40]
    c = [Calculation(a=4, b=5, c=n) for n in EXTERNAL_C]
    return c


K = []
f = foo()
queue = Queue()
for id, M in enumerate(f):
    p = Process(target=M.getdata, args=(id, queue))
    p.start()
    K.append(p)
for process in K:
    process.join()

results = [queue.get() for i in range(len(f))]
print(results)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65610002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档