我有一个循环:
listGames = []
for home in range(totalPlayers - 1):
for away in range(home + 1, totalPlayers):
listGames.append((home, away))
print listGames
match_num = 1
for game in listGames:
player1 = listPlayers[game[0]]
player2 = listPlayers[game[1]]
do_stuff(player1, player2)
当有很多玩家时,这个循环可能需要相当长的时间,所以我们希望使用线程来更快地完成循环。但是,player1和player2是类的实例,因此同时使用它们进行操作是不好的。编辑:这些“任务”的执行顺序在其他方面并不重要。你知道吗
我找到了http://www.troyfawkes.com/learn-python-multithreading-queues-basics/,这似乎正是我想要的,但我不确定如何调整它以确保一次只运行一个类/播放器实例
(简单)示例:
totalPlayers = 4
0, 1, 2, 3
listGames = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
所以,游戏(0,1),(2,3)可以同时执行,但是其他的必须等到这些完成
提示/想法?你知道吗
下面是一个示例程序,它展示了一种方法。其思想是创建一个
multiprocessing.Pool
来同时运行do_stuff
的多个实例。我们还维护一个set
来跟踪当前由do_stuff
实例处理的所有播放器,这样我们就不会同时处理同一个播放器多次。当do_stuff
完成它的工作时,它告诉父进程它已经完成了对播放器的处理,这样就可以处理使用这些播放器的新任务。你知道吗输出:
除非
do_stuff()
是IO绑定的,否则这可能会使您的代码because of the global interpreter lock变慢。基于您所说的“当有很多玩家时,这可能需要时间”的说法,我倾向于认为您的程序可能是CPU受限的—在这种情况下,多线程可能会损害您的性能。你知道吗说到你原来的问题,你要的是两个元素子集中的exact cover,不幸的是,这是NP完全的。你知道吗
相关问题 更多 >
编程相关推荐