MPSC makes program slow

Hello

I have a file of which I want to retrieve the content from each 10 seconds. To do this I use a infinite loop slowed down by a sleep of 10 seconds. To not make my application block due to the infinite loop I run it in a separate thread. The problem is that the content of the file needs to be accessible outside the thread.

I thought MPSC was ideal for this.

    let (tx, mut rx) = std::sync::mpsc::channel();
    std::thread::spawn(move|| {
        loop {
            let mut content = std::fs::read_to_string("logs.txt").expect("Couldn't read settings file.'");
            tx.send(content).unwrap();
            std::thread::sleep(std::time::Duration::from_secs(10));
        }
    });

    while let Ok(msg) = rx.recv() {
      // DO THINGS OUTSIDE THREAD
        println!("msg {msg}");
    }

It kinda works but it makes my program really slow and after a while it does not respond anymore. How to fix this?

Edit:
Is also tried Notify but that just does nothing, not even when deleting or editing a file.

     let mut watcher = notify::recommended_watcher(|res| {
        match res {
           Ok(event) => println!("event: {:?}", event),
           Err(e) => println!("watch error: {:?}", e),
        }
    }).unwrap();

    // Add a path to be watched. All files and directories at that path and
    // below will be monitored for changes.
    watcher.watch(std::path::Path::new("logs.txt"), RecursiveMode::NonRecursive).unwrap();

This seems to work better. Is this the best solution?

     let (sender, receiver) = glib::MainContext::channel(glib::source::Priority::default());
       gio::spawn_blocking(move || {
              loop {
                let mut content = std::fs::read_to_string("logs.txt").expect("Couldn't read settings file.'");
                sender.send(content).unwrap();
                std::thread::sleep(std::time::Duration::from_secs(10));
             }
        });


       receiver.attach(
    None,
    move |msg: String| {
        println!("rofl {:?}", msg);
        glib::ControlFlow::Continue
    },
);

Yes, if you are trying to perform communication between the GTK main thread and another thread you spawned, you should use the channel from glib and attach the receiver to the context you want to send messages to (the main context in this case, since you passed None)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.