Python Multiprocessing Implementation with Pools

I am trying to get some multithreading experience in Python. I use the game to do this, but I am having strange synchronization problems that create very strange errors in my game. The following is what I consider the appropriate code (the project is 500 lines, no need to overload it)

I have a game object that controls aspects of the user interface and passes your commands to the player object. My plan was to create the pool basically and pass the pool to the processEvents () methods for my player / computer, which will be used for large jobs.

import sys from Player import Player from AI import AI from multiprocessing import Pool, cpu_count class RTSGame(object): def processEvents(self): self.player.processEvents(self.ai.getShips(), pool) self.ai.processEvents(self.player.getUnits(), pool) #end processEvents if __name__ == '__main__': game = RTSGame() pool = Pool(processes=cpu_count()) game.main() 

Ultimately, the pool object ends here:

 def findTarget(self, targets, pool): ''' Returns the target best meeting the search criteria. Currently just does closest. Will add criteria for strongest, weakest, or type. ''' results = pool.map(findTargetHelper, map(lambda target: (self, target), targets)) shortest = min(results) if shortest[0] < self.attackinfo.getRange(): return shortest[1] #return the ship at shortest distance else: return None #return nothing ''' Old Code shortest = self.attackinfo.getRange() #You must be within the range of your weapons shortestTarget = None distfunc = self.getDistance for target in targets: dist = distfunc(self.position, target.getPosition()) if dist < shortest: shortest = dist shortestTarget = target return shortestTarget ''' #end findTarget() def findTargetHelper(target): #target[0] is assumed to be the one searching for a target return (target[0].getDistance(target[0].getPosition(), target[1].getPosition()), target[1]) 

Note that findTargetHelper () is not a method of this object (to get around the problem of splitting). Using my old code, it works fine, but may take a little time with a lot of objects.

My problems are weird. It seems that nothing is updated when objects change (for example, by causing damage through attacks).

I think I am missing something important in my code to make this work. And I want this to work, since I have other areas in which I could use this (for example, processor intensity is required for drawing).

Editing: I did a lot of research trying to figure this out. My research was unsuccessful. I would be grateful for any help you can give!

+4
source share

Source: https://habr.com/ru/post/1491373/


All Articles