伙计, 我有一个问题。我是一个Python编写的脚本,它由几个模块组成。某些模块依赖于其他模块,因此只有在依赖模块成功运行后才能运行它们。因此,每个模块都是从一个基类模块中派生出来的,并覆盖一个名为DEPENDENCIES的列表,这个列表是在模块运行时需要满足的依赖关系列表。有一个模块需要在所有其他模块之前运行。目前我正在做这样的事情。算法找到独立集合
modules_to_run.append(a)
modules_to_run.append(b)
modules_to_run.append(c)
.....
.....
modules_to_run.append(z)
# Very simplistically just run the Analysis modules sequentially in
# an order that respects their dependencies
foundOne = True
while foundOne and len(modules_to_run) > 0:
foundOne = False
for module in modules_to_run:
if len(module.DEPENDENCIES) == 0:
foundOne = True
print_log("Executing module %s..." % module.__name__, log)
try:
module().execute()
modules_to_run.remove(module)
for module2 in modules_to_run:
try:
module2.DEPENDENCIES.remove(module)
except:
#module may not be in module2's DEPENDENCIES
pass
except Exception as e:
print_log("ERROR: %s did not run to completion" % module.__name__, log)
modules_to_run.remove(module)
print_log(e, log)
for module in modules_to_run:
name = module.__name__
print_log("ERROR: %s has unmet dependencies and could not be run:" % name, log)
print_log(module.DEPENDENCIES, log)
现在我看到一些模块需要很长时间才能执行并且脚本运行时间过长。所以我想让它成为多线程,以便独立模块可以同时运行,从而节省时间。所以我想要一个解决方案,在每次迭代之后,我将重新计算'n'个独立模块(其中'n'是线程的最大数量,通常以2开始),并行执行并等待它们在下一次迭代之前完成。我对算法知之甚少,所以我被卡住了。你可以帮助我找到一种算法,在每次迭代之后发现最大'n'组独立模块,这些模块彼此之间没有任何依赖关系。
虽然我无法主动回答主要问题,但我可以说python实现线程化的方式可能不会有太多的性能增益(如果有的话),除非使用多个进程,听起来像是一团糟为了这。 – 2010-03-07 07:52:49
如果执行时间被文件I/O(或网络I/O等)膨胀,则线程可能没有问题。否则,请查看Python 2.6的多处理库。它们具有与线程模块类似的API,并且它们非常简单易用。 – detly 2010-03-07 08:26:05