我正在尝试通过使用 multiprocessing.Pool
来让我的程序更快地处理数据,但是我在实现它时遇到了一些问题。
我的程序有一个主文件,我在其中运行了 tkinter GUI,如下所示:
WIDTH = 1345
HEIGHT = 665
root = tk.Tk()
Calculate(Config, matrices):
(Calls the function Manager(), which is stored in another .py)
def main():
--variables, bindings and stuff--
btncalc.bind('<Button-1>', lambda event: Calculate(Config=Config,matrices=matrices))
if __name__ == '__main__':
main()
然后,如果用户点击按钮,函数 Calculate
调用管理数据处理的函数,并存储在另一个 .py 中。这是我使用 multiprocessing.Pool
的地方。另一个文件上的代码与此类似:
def worker(lista):
a,b,c,d,e = lista
(processing)
return [f,g,h,i]
def MultiprocessingFunc(a,b,c,d,e):
lista = []
results = []
for p in range(len(a)):
lista.append([a[p],b,c,d,e])
pool = Pool(os.cpu_count()) #in my case this is 4
results.append(pool.map(worker, lista)) #Hangs here sometimes
pool.close()
pool.join() #Hangs here if imap
return results
def Manager(Config, matrices):
(prepares stuff)
results = MultiprocessingFunc(a,b,c,d,e)
(uses the results)
有趣的是,有时这段代码确实有效,有时它只是挂在 pool.map
上。我不知道为什么它有时会一直挂起,但有时它确实可以正常工作。也许我应该使用 Process
和 Queue
而不是 Pool
?由于它只是无限期挂起,因此没有错误消息,所以我不知道从哪里开始调试代码。我不知道这是否重要,但我使用的是 Python3.8。