Python GTK+ 3 Safe Threading

故事扮演 提交于 2019-11-28 01:32:51
lazka

https://wiki.gnome.org/Projects/PyGObject/Threading

.. but, Gdk.threads_init() is deprecated, and I'd recommmend to:

  • Not call Gdk.threads_init, Gdk.threads_enter/leave at all
  • Use GLib.idle_add instead of Gdk.threads_add_idle (or any other Gdk.threads_* function)
  • Push things touching Gdk/Gtk to the main thread using GLib.idle/timeout_add

Why?:

  • Not calling Gdk.threads_init means there will be no lock, which is OK if you never access GDK from another thread.
  • Gdk.threads_enter does nothing since there is no lock.
  • GLib.idle_add is equal to Gdk.threads_add_idle in this case.

Regarding other libs:

  • Some GI modules can emit certain signals/callbacks in other threads (in GStreamer the GstPlayBin::about-to-finish signal for example); even if you don't use Python threads in your code at all. Gdk/Gtk code can't be called in them directly, use idle_add there as well if needed.
  • Many parts of GLib/GStreamer are thread safe and can be called from other threads.

tl;dr: Only GObject.threads_init(), in threads push all Gtk/Gdk code to the main thread using GLib.idle_add

Here is a must to read document if anyone is going to use GTK in multithreaded code. https://wiki.gnome.org/Attic/GdkLock

This document really helped me to understand how to run GTK from C as well as from python (through PyGTK just to import gtk in python) in a single process. Though the GDK Lock can be avoided in Linux by XInitThreads() it is not a solution for Windows. The Functions like g_idle_add() or g_timeout_add() are the generic solution to prevent GUI crush. However gdk_threads_enter() and gdk_thread_leave() are not completely useless yet. That document clarifies how to safely use those locks if someone wants to update GUI from different threads or from custom event handler or from g_idle_add() callbacks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!