Python GTK + 3安全线程 [英] Python GTK+ 3 Safe Threading

查看:121
本文介绍了Python GTK + 3安全线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我应该在程序的开头运行什么以使其具有线程安全性(或我在某些地方已经读过的线程感知型):

So what should I run at the beginning of my program to make it thread-safe (or thread-aware as I've read in some places):

from gi.repository import Gtk, Gdk, GLib, GObject
import threading

GLib.threads_init()     # ?
GObject.threads_init()  # YES!
Gdk.threads_init()      # ?

my_app()

def my_threaded_func():
   Glib.idle_add(lambda: some_gui_action())
   Glib.timeout_add(300, lambda: some_gui_action())

t = threading.Thread(target=my_thread_func)
t.daemon = True
t.start()

Gtk.main()

然后,我应该在线程中做什么?某种锁?使用Python的线程库是否安全?还是应该在GLib,GObject或Gdk中使用某些内容?我知道那里有很多问题/答案/示例,但是它们彼此矛盾,不是针对Gtk + 3,不是针对Python,或者根本就不完整,甚至我认为是Python GI的官方文档( http://lazka.github.io/pgi-docs/)甚至都没有提到存在GObject.threads_init()和Gdk.threads_init()的对象.

Then, what should I do in my threads? Some kind of lock? Is it safe to use Python's threading library or should I use something in GLib, GObject or Gdk? I know there is a ton of questions/answers/examples out there, but they all contradict each other, are not for Gtk+ 3, or not for Python, or simply incomplete, and even what I considered the official docs for Python GI (http://lazka.github.io/pgi-docs/) does not even mention the existence of GObject.threads_init() and Gdk.threads_init().

推荐答案

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

..但是 Gdk.threads_init()是不推荐使用,我建议:

  • 根本不调用Gdk.threads_init,Gdk.threads_enter/离开
  • 使用GLib.idle_add代替Gdk.threads_add_idle(或任何其他Gdk.threads_ *函数)
  • 使用GLib.idle/timeout_add将触摸Gdk/Gtk的东西推入主线程

为什么?:

  • 不调用Gdk.threads_init表示将没有锁,如果您从不从另一个线程访问GDK,则可以.
  • 由于没有锁,Gdk.threads_enter不会执行任何操作.
  • GLib.idle_add等于在这种情况下为Gdk.threads_add_idle .

关于其他库:

  • 某些GI模块可以在其他线程中发出某些信号/回调(例如,在GStreamer中,GstPlayBin :: about-to-finish信号);即使您根本不在代码中使用Python线程.不能直接在其中调用Gdk/Gtk代码,如果需要,也可以在其中使用idle_add.
  • GLib/GStreamer的许多部分都是线程安全的,可以从其他线程中调用.

tl; dr:仅GObject.threads_init(),在线程中 使用 GLib.idle_add 将所有Gtk/Gdk代码推送到主线程>

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

这篇关于Python GTK + 3安全线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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