python queue.join()正在工作

时间:2015-03-13 15:41:24

标签: python multithreading join queue

我正在尝试在python中进行多处理计算,但由于某种原因,我无法控制新创建的进程的数量。几秒钟后,IDE在数百个新进程中被粉碎。 这是有问题的代码(从底部的expectiEvaluation开始):

   def serialExpecti(state, level):
    allPieces = [L(), T(), O(), Z(), I(), J(), S()]
    if level == 0:
        return expectiHelper(state) / len(allPieces)

    queueStates = util.PriorityQueueWithFunction(expectiHelper)
    evaluation = 0;
    for i in range(len(allPieces)):
        succsecors = findAllPossiblePositions(state, allPieces[i])
        for curState in succsecors:
            queueStates.push(curState)
        bestState = queueStates.pop() 
        evaluation += serialExpecti(bestState, level + 1)
        queueStates = util.PriorityQueueWithFunction(expectiHelper)  # clear queue   
#     print  evaluation  
    return evaluation   

def parallelExpecti(state, queue):
    print os.getpid()
    queue.put(serialExpecti(state, 0))



def expectiEvaluation(state):
     allPieces = [L(), T(), O(), Z(), I(), J(), S()]
     queue = multiprocessing.JoinableQueue()
     queueStates = util.PriorityQueueWithFunction(expectiHelper)
     for i in range(len(allPieces)):
         succsecors = findAllPossiblePositions(state, allPieces[i])  
         for curState in succsecors:
            queueStates.push(curState)
         bestState = queueStates.pop()
         p = multiprocessing.Process(target=parallelExpecti, args=(bestState, queue,))
         p.start()
     queue.join()
     evaluation = 0;
     while not queue.empty():
         evaluation += queue.get()
     return evaluation

serialExpecti()中的计算非常繁重,所以我想让它并行。 函数expectiEvaluation()在程序运行期间多次从主线程调用,我认为由于某种原因,queue.join()不会阻止执行,因此主线程不断破坏并调用expectiEvaluation ()使它创建越来越多的进程。 可能是什么问题?

更新 我试图摆脱queue.join()只是保持列表中的所有进程,并在函数的末尾加入它们,它工作...等等。现在这些流程都在控制之中,而不是像疯了一样创建,但程序运行速度非常慢。比纯串行版本慢得多。我究竟做错了什么? 也许如果我把串口版本放在这里会有所帮助:

 def expectiHelper(state):
    return 10*holesEvaluation(state) + fullRowEvaluation(state) +  heightEvaluation(state) + maxLengthEvaluation(state) + averageEvaluation(state)+ medianEvalutaion(state)

def expectiEvaluation(state, level=0):
    global problem
    allPieces=[L(), T(), O(), Z(),  I(),  J(),  S()]
    if level==3:
        return expectiHelper(state)/len(allPieces)

    queueStates = util.PriorityQueueWithFunction(expectiHelper)
    evaluation=0;
    for i in range(len(allPieces)):
        succsecors = problem.findAllPossiblePositions(state,allPieces[i])
        for curState in succsecors:
            queueStates.push(curState)
        bestState =  queueStates.pop() 
        evaluation+= expectiEvaluation(bestState, level+1)  #add best evaluation for this piece
        queueStates = util.PriorityQueueWithFunction(expectiHelper) #clear queue   
#     print  evaluation  
    return evaluation  

你可以看到它是一个递归函数,这个循环中的每个迭代都是独立的,非常非常重,所以我可以并行执行:

for i in range(len(allPieces)):

0 个答案:

没有答案