Python多处理共享类型数组 - 无法写入

时间:2013-10-07 16:14:35

标签: python multiprocessing

出于测试原因,我只启动了1个进程。一个给定的参数是一个应该从该过程改变的数组。

class Engine():
Ready = Value('i', False)

def movelisttoctypemovelist(self, movelist):
    ctML = []
    for zug in movelist:
        ctZug = ctypeZug()
        ctZug.VonReihe = zug.VonReihe
        ctZug.VonLinie = zug.VonLinie
        ctZug.NachReihe = zug.NachReihe
        ctZug.NachLinie = zug.NachLinie
        ctZug.Bewertung = zug.Bewertung
        ctML.append(ctZug)
    return ctML

def findbestmove(self, board, settings, enginesettings):
    print ("Computer using", multiprocessing.cpu_count(),"Cores.")
    movelist = Array(ctypeZug, [], lock = True)
    movelist = self.movelisttoctypemovelist(board.movelist)
    bd = board.boardtodictionary()
    process = []
    for i in range(1):
        p = Process(target=self.calculatenullmoves, args=(bd, movelist, i, self.Ready))
        process.append(p)
        p.start()
    for p in process:
        p.join()
    self.printctypemovelist(movelist, settings)
    print ("Ready:", self.Ready.value)

def calculatenullmoves(self, boarddictionary, ml, processindex, ready):
    currenttime = time()
    print ("Process", processindex, "begins to work...")
    board = Board()
    board.dictionarytoboard(boarddictionary)
    ...
    ml[processindex].Bewertung = 2.4
    ready.value = True
    print ("Process", processindex, "finished work in", time()-currenttime, "sec")

def printctypemovelist(self, ml):
    for zug in ml:
        print (zug.VonReihe, zug.VonLinie, zug.NachReihe, zug.NachLinie, zug.Bewertung)

我尝试直接在列表中编写2.4,但在调用“printctypemovelist”时没有显示更改。 我将“Ready”设置为True并且它可以工作。 我使用了来自http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.sharedctypes

的信息

我希望有人能找到我的错误,如果它太难读,请告诉我。

1 个答案:

答案 0 :(得分:0)

问题是你正在尝试共享一个普通的Python列表:

ctML = []

改为使用代理对象:

from multiprocessing import Manager
ctML = Manager().list()

有关详细信息,请参阅Sharing state between processes上的Python文档。