Search code examples
classpython-3.xtkintermultiprocessingpython-multiprocessing

Python - Integration of multiprocessing with classes


I have a problem in Python with the module multiprocessing. Basically, I'm making a game (with tkinter as graphics)  in which I have a class Game and several classes (entites) that all have an update(self) method. So it's a bit like:

class Game:
  __init__(self, etc...):
    self.entities = []
  gameloop(self):
     for entity in self.entities:
       entity.update

class EntityExample:
  __init__(self, game, etc...):
    self.game = game
  update(self):
    #stuff

   

And then I do:

game = Game() 
game.entities.append(EntityExample()) 
game.gameloop()

So I tried, to optimize the code, to do a thing like that:

import multiprocessing

class Game:
  __init__(self, etc...):
    self.entities = []
    self.threads = []
    self.lock = multiprocessing.Lock()
  gameloop(self):
     for entity in self.entities:
       entity.update

class EntityExample:
  __init__(self, game, etc...):
    self.game = game
  update(self):
    self.game.lock.acquire() 
    #stuff
    self.game.lock.release()

And in gameloop:

for entity in entities:
  t = multiprocessing.Process(target=entity.update)
  t.start()
  t.join
  self.threads.append(t)

The goal was to do the calculations on different cores at the same time to improve performance, but it doesn't work sadly. I also asks to kill the program in IDLE: "The program is still running. Do you want to kill it?".

Thanks in advance,

Talesseed

P.S. : the classes are not picklable

P.P.S. : I've read that create a new Process copies the code inside the file to a new thread, and that could be a problem because my code is ~1600 lines long.


Solution

  • I found something interesting. Apparently, running it through the console make it work. But I've done some testing and the multithreaded version is in fact slower that the single threaded version. I've no clue :/

    EDIT: Nevermind, it works now, my bad.