gtk-rs:如何从其他线程更新视图



我正在使用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(循环?

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

谢谢你的帮助!

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

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

  1. 创建一种不涉及传递闭包的方法来在线程之间发送数据。我现在使用std::sync::mpsc,但另一种选择可能更好的长期。创建一些线程本地全局存储。在启动第二个线程之前,将UI引用和通信管道的接收端全局存储在主线程中。
  2. 通过闭包将通道发送端传递给第二个线程。把你想要的数据传递给那个发送者。
  3. 在传递数据后,使用glib::idle_add()(不是闭包,而是静态函数)告诉UI线程检查通道中是否有新消息。在UI线程的静态函数中,访问全局UI和receiver变量并更新UI。

感谢这个线程帮助我弄清楚。下面是我的代码:

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);
}
});
}