所以我开始尝试Python的多处理库。我的目标是加速一个慢函数,该函数将一个字符串与其他字符串的大型数据库进行比较,并返回最相似的匹配。为此,我尝试编写一个函数,在不同的流程对象之间拆分任务并设置它们运行,使用共享变量来捕获结果:
cores = cpu_count() # Number of cores in this computer, i.e. 4
sublistList = chunks(tasks,cores) # Split tasks into subprocessing arrays of evenly-sized chunks, the number of chunks equal to how many cores we have to process them
# Create a multiprocessing function, since this is a large function that will take time and splitting it across cores will ease the load
if __name__ == '__main__':
freeze_support() # Make sure multiple applications don't spawn, this is necessary for Windows
jobs = [] # Array of processes
manager = Manager() # Create a manager
returns = manager.list() # Shared list variable we use to get return results
for i in range(0,cores): # For number of cores...
p = Process(target=workerFunction,args=(w,sublistList[i],returns))
jobs.append(p) # Add to array of processes to run
p.start()
for p in jobs:
p.join()
然而,当我运行这段代码时,它会创建一个新的应用程序窗口,然后无限期地挂起,这是完全奇怪的行为,完全不是我想要的。是什么导致了我的代码中出现这种情况?我的工作程序是否在无声地崩溃而没有提醒我?我看了其他各种各样的答案,但没有一个建议的答案可以解决这个问题。在
(如果这与问题有关,我是一个初级软件工程师,有几年其他语言的编程经验,但对Python比较陌生。这是我的一个小型独立游戏项目。)
这还不是答案,但我发布它是为了向您展示一个可运行Minimal, Complete, and Verifiable Example的示例。在
该代码基于您当前的问题,加上其他所有使其可运行所缺少的内容。毫不奇怪,因为所有这些都只是猜测,它不会重现您所说的问题,但这很可能是因为我的一个或多个猜测在某些重要方面有所不同……这就是为什么您真的应该提供所有代码。在
一个观察:最后的
p.join()
调用将使主进程等待每个子进程完成。这将导致主进程在等待每个进程时显示为“挂起”。在输出:
^{pr2}$相关问题 更多 >
编程相关推荐