問題描述
以下代碼在linux中的python 3.2.2中沒有做任何事情就掛起:
The following code hangs without doing anything in python 3.2.2 in linux:
import tkinter
from multiprocessing import Process
def f():
root = tkinter.Tk()
label = tkinter.Label(root)
label.pack()
root.mainloop()
p = Process(target=f)
p.start()
我找到的關于這個問題的唯一信息是 issue 5527,其中指出問題出在 tkinter
在進程被分叉之前被導入,可以通過在函數(shù) f
中導入 tkinter
來修復,并且該問題在 Linux 中出現(xiàn)但不是索拉里斯.
The only information I have found about this problem is issue 5527, in which it is noted that the problem is with tkinter
being imported before the process is forked, that it can be fixed by importing tkinter
inside the function f
, and that the problem occurs in Linux but not Solaris.
有誰知道究竟是什么導致了這個問題,是故意的還是最終會得到解決?除了在我需要的任何地方本地導入 tkinter
之外,還有其他解決方法嗎(這看起來很糟糕)?其他模塊是否有類似的多處理問題?
Does anyone know what exactly is causing this problem, and if it is intentional or will eventually be fixed? Is there any workaround other than to import tkinter
locally everywhere I need it (which seems like bad style)? Do any other modules have similar issues with multiprocessing?
推薦答案
截至 2013 年 9 月,有一些關于錯誤報告的附加評論可以讓您更深入地了解實際問題.
As of September 2013, there are some additional comments on the bug report that give more insight into what the actual problem is.
http://bugs.python.org/issue5527#msg194848
http://bugs.python.org/issue5527#msg195480
基于上述情況,我猜測正在發(fā)生以下情況:Tkinter 不是線程安全的,因此(無論出于何種原因)Tkinter 想知道哪個線程是主線程.Tkinter 假設加載 Tkinter 模塊時的主線程也將是程序執(zhí)行的主線程.當你在加載 Tkinter 后 fork 或 multiprocess 時,這個假設就被打破了.(例如,fork 后,記住的主線程在父線程,而不是子線程.)
Based on the above, I'm guessing something like the following is happening: Tkinter is not thread safe, so (for whatever reason) Tkinter wants to know which thread is the main thread. Tkinter assumes that the main thread when the Tkinter module is loaded will also be the main thread for program execution. When you fork or multiprocess after loading Tkinter, this assumption is broken. (For example, after a fork, the remembered main thread is in the parent, not the child.)
這篇關于為什么 tkinter 不能很好地處理多處理?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!