Value moved into closure here, in previous iteration of loop

Hello I have a problem in new thread in rust

The error is value moved into closure here, in previous iteration of loop

I have to ping every x seconds another url.

let label: Label = builder.get_object("label").expect("Couldn't get label");
label.set_text("ping ko");
let label_clone = fragile::Fragile::new(label.clone());

thread::spawn(move || {
    loop{
        let request = nano_get::Request::default_get_request("https://www.test.com/Ping").expect("Failed to open request");
        let response: Response = request.execute().expect("Failed to get");
        if response.body.contains("PING OK") {
            glib::MainContext::default().invoke(move|| {
                label_clone.get().set_text("ping ok");
                });
            }
        let ping_polling: u64 = (select_ping_polling().expect("Select ping error")).parse::<u64>().unwrap();
        println!("{}", ping_polling);
        thread::sleep(time::Duration::from_secs(ping_polling));
        }
    });

Thanks
Gianluca

I assume the error message points to this piece of code? (If not, you should provide us with the exact error message.) You should be able to fix that by moving the

let label_clone = fragile::Fragile::new(label.clone());

into the loop, like this:

if response.body.contains("PING OK") {
    let label_clone = fragile::Fragile::new(label.clone());
    glib::MainContext::default().invoke(move|| {
        label_clone.get().set_text("ping ok");
    });
}

The first time invoke is called, label_clone is moved into the closure, so you can't use it anymore in the other iterations. The above code creates a new label_clone every time invoke is called, so each time, a new value is moved into the closure.

I try but if I put into the loop I get this error message:

*mut *mut gtk_sys::_GtkWidgetPrivate cannot be sent between threads safely
--> src/main.rs:291:5
|
291 | thread::spawn(move || {
| ^^^^^^^^^^^^^ *mut *mut gtk_sys::_GtkWidgetPrivate cannot be sent between threads safely

You cannot use gtk from more than one thread at once. If you want to interact with gtk from another thread, you will have to use channels to ask the main thread to do it. The glib crate provides a channel that integrates with gtk rather nicely.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.