Why doesn't tkinter play nicely with multiprocessing?

前端 未结 2 1690
说谎
说谎 2020-12-19 09:36

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(         


        
相关标签:
2条回答
  • 2020-12-19 09:44

    My suspicion is that the problem has to do with the connection to the X server (usually a socket). If this is created before the process is fork()-ed, the child process inherits this connection. But if it tries to use it, the X server gets confused.

    After a cursory look at at Tkinter.py, it looks like maybe calling the NoDefaultRoot function before starting the process might be useful. It all depends on when the connection to the X server is made.

    Otherwise importing Tkinter after the fork seems the way to go.

    0 讨论(0)
  • 2020-12-19 09:59

    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

    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.)

    0 讨论(0)
提交回复
热议问题