Python - 多处理与 类 的集成
Python - Integration of multiprocessing with classes
我在 Python 中遇到模块多处理问题。
基本上,我正在制作一个游戏(使用 tkinter 作为图形),其中我有一个 class 游戏和几个 classes(实体),它们都有一个 update(self) 方法。
所以有点像:
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
然后我做:
game = Game()
game.entities.append(EntityExample())
game.gameloop()
所以我尝试优化代码,做这样的事情:
导入多处理
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()
在游戏循环中:
for entity in entities:
t = multiprocessing.Process(target=entity.update)
t.start()
t.join
self.threads.append(t)
目标是同时在不同的核心上进行计算以提高性能,但遗憾的是它并没有奏效。
我还要求在 IDLE 中终止程序:"The program is still running. Do you want to kill it?"。
提前致谢,
Talesseed
P.S。 : classes 不可腌制
P.P.S。 : 我读过创建一个新进程将文件中的代码复制到一个新线程,这可能是个问题,因为我的代码长约 1600 行。
我发现了一些有趣的东西。显然,运行 它通过控制台使其工作。但我做了一些测试,多线程版本实际上比单线程版本慢。我不知道 :/
编辑:没关系,它现在可以工作了,我的错。
我在 Python 中遇到模块多处理问题。 基本上,我正在制作一个游戏(使用 tkinter 作为图形),其中我有一个 class 游戏和几个 classes(实体),它们都有一个 update(self) 方法。 所以有点像:
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
然后我做:
game = Game()
game.entities.append(EntityExample())
game.gameloop()
所以我尝试优化代码,做这样的事情:
导入多处理
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()
在游戏循环中:
for entity in entities:
t = multiprocessing.Process(target=entity.update)
t.start()
t.join
self.threads.append(t)
目标是同时在不同的核心上进行计算以提高性能,但遗憾的是它并没有奏效。 我还要求在 IDLE 中终止程序:"The program is still running. Do you want to kill it?"。
提前致谢,
Talesseed
P.S。 : classes 不可腌制
P.P.S。 : 我读过创建一个新进程将文件中的代码复制到一个新线程,这可能是个问题,因为我的代码长约 1600 行。
我发现了一些有趣的东西。显然,运行 它通过控制台使其工作。但我做了一些测试,多线程版本实际上比单线程版本慢。我不知道 :/
编辑:没关系,它现在可以工作了,我的错。