【发布时间】:2016-01-19 12:15:38
【问题描述】:
我在 Python 中遇到了模块 multiprocessing 的问题。 基本上,我正在制作一个游戏(以 tkinter 作为图形),其中我有一个 Game 类和几个类(实体),它们都有一个 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 中杀死程序:“程序仍在运行。你想杀死它吗?”。
提前致谢,
神来之笔
附: : 类不可腌制
附言:我读过 create a new Process 会将文件中的代码复制到新线程,这可能是个问题,因为我的代码长约 1600 行。
【问题讨论】:
-
为什么所有代码的每一行都以连字符开头?
-
@BryanOakley 哎呀,我会删除它
-
'init'、gameloop 或 update 均未声明为函数,并且 update 缺少自我,因此不是 EntityExample 的一部分
标签: class python-3.x tkinter multiprocessing python-multiprocessing