Mongoengine Document在多处理映射后重置属性值

时间:2017-04-11 16:53:24

标签: python multiprocessing mongoengine

我有一个很大的元素列表~100000,需要按如下方式映射:

def mark_diff(args):
    item = args[0]
    pi = args[1]
    item.marked_diff = (item.p/pi[0]+item.c/pi[1]+item.f/pi[2] - 3)**2
    return item

def mark(f_set , goal):
    with Pool(3) as p:
        data = p.map(mark_diff , zip(f_set , itertools.repeat(goal)))
    return data

item.markded_diff的默认值为0itemmongoengine document

我正在使用多处理,因为mark_diff比这里显示的要复杂得多,并且涉及很多指数,我使用numpy的对数。

现在出现问题,

返回的data仍然item.marked_diff0。 如果我在mark_diff的底部添加一个打印语句,则正在分配正确的值且非零。

项目的定义。

    import random,mongoengine
    class F(mongoengine.Document):
        p = mongoengine.FloatField()
        c = mongoengine.FloatField()
        f = mongoengine.FloatField()
        marked_diff = 0
    f_sets = F.objects.all()    
    goal = [0.2,0.35,0.45]

1 个答案:

答案 0 :(得分:1)

所以没有显示的内容正在发生。当我把它变成一个完整的,可执行的程序时,它似乎工作正常。这是Python 3.6.1下一次运行的输出:

0.7024116548559156
13.468354599594324
6.036133666404753
0.16520292241977205
0.17073749475275496
1.903674418518389
0.2432159511273063
7.743326563037492
4.1990243814914425
19.36243187965931

这是完整的程序:

from multiprocessing import Pool
import random
import itertools

class F:
    def __init__(self):
        self.p = random.random()
        self.c = random.random()
        self.f = random.random()

def mark_diff(args):
    item = args[0]
    pi = args[1]
    item.marked_diff = (item.p/pi[0]+item.c/pi[1]+item.f/pi[2] - 3)**2
    return item

def mark(f_set , goal):
    with Pool(3) as p:
        data = p.map(mark_diff , zip(f_set , itertools.repeat(goal)))
    return data

if __name__ == "__main__":
    f_set = [F() for _ in range(10)]
    goal = [0.2,0.35,0.45]
    xs = mark(f_set, goal)
    for x in xs:
        print(x.marked_diff)

您是否有可能在原始marked_diff中查看f_set而不是mark()返回的项目?