【问题标题】:gtk-rs: how to update view from another threadgtk-rs:如何从另一个线程更新视图
【发布时间】:2021-03-08 02:14:25
【问题描述】:

我正在使用gtk-rs 创建一个 UI 应用程序。在那个应用程序中,我必须生成一个线程来不断地与另一个进程通信。有时,我必须根据该线程中发生的情况更新 UI。但是,我不确定如何执行此操作,因为我无法跨线程保存对 UI 任何部分的引用。

这是我试过的代码:

use gtk;

fn main() {
    let application =
        gtk::Application::new(Some("com.github.gtk-rs.examples.basic"), Default::default()).unwrap()

    application.connect_activate(|app| {
        let ui_model = build_ui(app);
        setup(ui_model);
    });

    application.run(&[]);
}

struct UiModel { main_buffer: gtk::TextBuffer }

fn build_ui(application: &gtk::Application) -> UiModel {
    let glade_src = include_str!("test.glade");
    let builder = gtk::Builder::new();
    builder
        .add_from_string(glade_src)
        .expect("Couldn't add from string");

    let window: gtk::ApplicationWindow = builder.get_object("window").unwrap();
    window.set_application(Some(application));
    window.show_all();

    let main_text_view: gtk::TextView = builder.get_object("main_text_view")

    return UiModel {
        main_buffer: main_text_view.get_buffer().unwrap(),
    };
}

fn setup(ui: UiModel) {
    let child_process = Command::new("sh")
        .args(&["-c", "while true; do date; sleep 2; done"])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    let incoming = child_process.stdout.unwrap();

    std::thread::spawn(move || {                              // <- This is the part to pay
        &BufReader::new(incoming).lines().for_each(|line| {   //    attention to.
            ui.main_buffer.set_text(&line.unwrap());          //    I am trying to update the
        });                                                   //    UI text from another thread.
    });
}

但是,我得到了错误:

    |       std::thread::spawn(move || {
    |  _____^^^^^^^^^^^^^^^^^^_-
    | |     |
    | |     `*mut *mut gtk_sys::_GtkTextBufferPrivate` cannot be sent between threads safely

这是有道理的。我可以理解 Gtk 小部件不是线程安全的。但是那我该如何更新它们呢?有没有办法安全地向 UI 线程发送信号?或者有没有办法以不阻塞 UI 的方式在同一线程中运行 .lines().for_each( 循环?

无论我采用什么解决方案,都必须具有非常高的性能。我将发送比示例中更多的数据,并且我希望屏幕刷新延迟非常低。

感谢您的帮助!

【问题讨论】:

  • 我还没有在 Rust 中做过这个,所以一些一般性的手波建议:如果你有一个快速工作的线程并且有很多数据,你可能无法轻松地为数据创建快照图形用户界面。因此,请确保您可以将其锁定在块中,这样工作线程就不会经常被阻塞。然后我会做你需要在 GUI 中做的事情,只读取屏幕上实际项目的数据。不要创建所有数据的列表或表格视图。创建一个带有滚动条的视图,该滚动条在滚动时显示模糊,然后执行回调以拉取数据以显示 20 个实际可见的事物。这是某处的控制选项。
  • 要从线程更新 UI,您必须使用 g_idle_add() developer.gnome.org/glib/stable/… ..(这是 c 文档)

标签: multithreading rust gtk3 gtk-rs


【解决方案1】:

好的,我解决了这个问题。对于未来的任何人,这都是解决方案。

glib::idle_add(|| {}) 允许您从 UI 线程上的另一个线程运行闭包(感谢 @Zan Lynx)。这足以解决线程安全问题,但还不足以绕过借用检查器。没有GTKObject 在线程之间发送是安全的,所以另一个线程甚至永远不能持有对它的引用,即使它永远不会使用它。所以你需要在 UI 线程上全局存储 UI 引用,并在线程之间建立一个通信通道。这是我一步一步做的:

  1. 创建一种不涉及传递闭包的线程间发送数据的方法。我暂时使用了std::sync::mpsc,但从长远来看,另一种选择可能会更好。
  2. 创建一些线程局部全局存储。在您启动第二个线程之前,将您的 UI 引用和该通信管道的接收端全局存储在主线程上。
  3. 通过闭包将通道的发送端传递给第二个线程。通过该发件人传递您想要的数据。
  4. 在传递数据后,使用glib::idle_add()(不是使用闭包而是使用静态函数)告诉 UI 线程检查通道中的新消息。
  5. 在 UI 线程上的静态函数中,访问您的全局 UI 和接收器变量并更新 UI。

感谢 this thread 帮助我解决这个问题。这是我的代码:

extern crate gio;
extern crate gtk;
extern crate pango;

use gio::prelude::*;
use gtk::prelude::*;
use std::cell::RefCell;
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::sync::mpsc;

fn main() {
    let application =
        gtk::Application::new(Some("com.github.gtk-rs.examples.basic"), Default::default())
            .unwrap();

    application.connect_activate(|app| {
        let ui_model = build_ui(app);
        setup(ui_model);
    });

    application.run(&[]);
}

struct UiModel {
    main_buffer: gtk::TextBuffer,
}

fn build_ui(application: &gtk::Application) -> UiModel {
    let glade_src = include_str!("test.glade");
    let builder = gtk::Builder::new();
    builder
        .add_from_string(glade_src)
        .expect("Couldn't add from string");

    let window: gtk::ApplicationWindow = builder.get_object("window").unwrap();
    window.set_application(Some(application));
    window.show_all();

    let main_text_view: gtk::TextView = builder.get_object("main_text_view").unwrap();

    return UiModel {
        main_buffer: main_text_view.get_buffer().unwrap(),
    };
}

fn setup(ui: UiModel) {
    let (tx, rx) = mpsc::channel();
    GLOBAL.with(|global| {
        *global.borrow_mut() = Some((ui, rx));
    });
    let child_process = Command::new("sh")
        .args(&["-c", "while true; do date; sleep 2; done"])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    let incoming = child_process.stdout.unwrap();

    std::thread::spawn(move || {
        &BufReader::new(incoming).lines().for_each(|line| {
            let data = line.unwrap();
            // send data through channel
            tx.send(data).unwrap();
            // then tell the UI thread to read from that channel
            glib::source::idle_add(|| {
                check_for_new_message();
                return glib::source::Continue(false);
            });
        });
    });
}

// global variable to store  the ui and an input channel
// on the main thread only
thread_local!(
    static GLOBAL: RefCell<Option<(UiModel, mpsc::Receiver<String>)>> = RefCell::new(None);
);

// function to check if a new message has been passed through the
// global receiver and, if so, add it to the UI.
fn check_for_new_message() {
    GLOBAL.with(|global| {
        if let Some((ui, rx)) = &*global.borrow() {
            let received: String = rx.recv().unwrap();
            ui.main_buffer.set_text(&received);
        }
    });
}

【讨论】:

  • 仅供参考,还有glib::source::idle_add_once,它可能更适合您的特定用例,也可能不适合。
  • 另外值得注意的是idle_add 可能会占用您的 CPU,因为根据定义,它会在线程空闲时运行。对于 GUI 上需要定期更新的东西,使用glib::source::timeout_add 可能更合适,以避免不必要的高 CPU 使用率。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2020-07-13
相关资源
最近更新 更多