rust Fltk通道接收器丢失一些消息

6tdlim6h  于 2023-03-02  发布在  其他
关注(0)|答案(2)|浏览(134)

我创建了一个带有按钮的fltk窗口,当单击按钮时,按钮会生成一个线程,其中包含10次迭代,每次迭代都会向通道发送一条消息,使用println!()时一切正常,但如果我删除它,通道就会开始跳过一些消息。

[dependencies]
fltk = { version="1.2.23", features=["fltk-bundled"] }
fltk-evented = "0.1"
use fltk::{prelude::*, *};
use std::{cell::RefCell, rc::Rc, thread};

fn main() {
    //create channel
    let (mainSender, mainReceiver) = app::channel::<i32>();

    //create application, window, button
    let mainApp = app::App::default();
    let mut win = window::Window::default().with_size(500, 500);
    let mut btn = button::Button::new(20, 20, 100, 40, "START");

    win.end();
    win.show();

    let mainSenderClone = mainSender.clone();

    btn.handle(move |thisBtn, evt| match evt {
        //btn event handler
        enums::Event::Push => {
            //click event

            thread::spawn(move || {
                //create thread

                let mut cnt = 0; //10 iterations
                while (cnt < 10) {
                    mainSenderClone.send(cnt);
                    //println!("sent_from_thread: {}",cnt); - uncommenting this fixes the situation
                    cnt += 1;
                }
            });

            true //event handled
        }

        _ => false, //ignore other events
    });

    //start listening
    while mainApp.wait() {
        if let Some(msg) = mainReceiver.recv() {
            println!("RECEIVED: {}", msg);
        }
    }
}

输出(线程中没有println!()):

RECEIVED: 1
RECEIVED: 3
RECEIVED: 5
RECEIVED: 7
RECEIVED: 9

使用println!():

sent_from_thread: 0
RECEIVED: 0
sent_from_thread: 1
RECEIVED: 1
sent_from_thread: 2
RECEIVED: 2
sent_from_thread: 3
RECEIVED: 3
sent_from_thread: 4
RECEIVED: 4
sent_from_thread: 5
RECEIVED: 5
sent_from_thread: 6
RECEIVED: 6
sent_from_thread: 7
RECEIVED: 7
sent_from_thread: 8
RECEIVED: 8
sent_from_thread: 9
RECEIVED: 9
qlzsbp2j

qlzsbp2j1#

所以,在学习了几天魔法之后,我决定做“货物更新+构建”,然后一切都开始正常工作。
我仍然不太明白那是什么,以及以前下载的依赖项是如何损坏的,但是...是的,更新修复了它
还有一个问题,我还是不明白为什么有时候频道会立刻收到所有的10条信息,有时候会收到0123 [暂停1-2秒] 456789。但是我想我最终会找到答案的
感谢所有接受我的代码并进行测试的人,特别是@denys-séguret,@joe-jingyu

agxfikkp

agxfikkp2#

我有类似的问题,接收器丢失了几乎一半的事件。
我的问题是因为有两个app:channels和两个app::add_idle3
当我删除其中一个app::add_idle3时,另一个app开始接收所有事件。

let (sender_window, receiver_area): (Sender<[usize; 2]>, Receiver<[usize; 2]>) = app::channel();
let (sender_machine, receiver_frame): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = app::channel();

app::add_idle3(move |_| {
    if let Some(msg) = receiver_frame.recv() {
    ...    
}
});
app::add_idle3(move |_| {
    if let Some(msg) = receiver_area.recv() {
    ...    
    }
});

在我看来像是fltk-rs病毒。

相关问题