为什么tkinter在多处理中不能很好地发挥作用? [英] Why doesn't tkinter play nicely with multiprocessing?

查看:98
本文介绍了为什么tkinter在多处理中不能很好地发挥作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在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()

我找到的有关此问题的唯一信息是问题5527 ,其中指出问题出在在派生该过程之前被导入,可以通过在函数f中导入tkinter来解决该问题,并且该问题在Linux中发生,但在Solaris中不存在.

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

基于以上所述,我猜测正在发生以下类似情况:Tkinter不是线程安全的,因此(无论出于何种原因)Tkinter都想知道哪个线程是主线程. Tkinter假定加载Tkinter模块时的主线程也将是程序执行的主线程.当您在加载Tkinter之后进行分叉或多进程时,此假设将被破坏. (例如,在分叉之后,记住的主线程位于父级中,而不是子级中.)

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在多处理中不能很好地发挥作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆