I would create a class Game
that is inherited from threading.Thread
, so it behaves similar to the thread. Game
class constructor accepts two player objects and number
of the game.
number
is required to facilitate returning of the game result into main program through the shared variable resultList
(lists are thread-safe in Python). resultList
is a list of lists and each Game
instance puts the result to the corresponding cell of resultList
according to its number
.
run()
method of each Game()
instance is executed in a different thread so all the games are going on in parallel.
import threading
numOfGames = 10
resultList = [[] for x in xrange(numOfGames)]
class Game(threading.Thread):
def __init__(self, player1, player2, number):
threading.Thread.__init__(self)
self.number = number
self.player1 = player1
self.player2 = player2
def run(self):
#Your game algorithm between self.player1 and self.player2 is here
#Put game result into shared list
resultList[self.number] = <result>
To work with the Game
class you do the following:
#Create instances of the Game() class, pass your Player() objects
#You can do the step in loop
game0 = Game(<PlayerObj>,<PlayerObj>,0)
game1 = Game(<PlayerObj>,<PlayerObj>,1)
#Start execution of Game.run() methods of all Game() objects in separate threads
#You can do the step in loop
game0.start()
game1.start()
#Wait until all Game.run() methods are executed = all threads are finished
#You can do the step in loop
game0.join()
game1.join()
#In the shared list you have corresponding return values,
#whatever they are in your case [[result of Game 0],[result of Game 1],[]...]
print resultList
PS: I wouldn't recommend to go with multiprocessing since there is a substantial overhead in creating a process (need to allocate stack etc.). In your case multiprocessing would suffice since your application has no need in memory isolation.