Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When a callback function is called multiple times in a thread, only the first call takes effect #1038

Closed
XiaoyuZhann opened this issue Apr 29, 2024 · 2 comments

Comments

@XiaoyuZhann
Copy link

Hello, I tested implementing a udpSocket connection in rust, but I can only receive the first value in js, and then print "un def". The frontend I'm using is Electron and the neon version is 1.0.0

RUST:

fn parse_async(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    let address = cx.argument::<JsString>(0)?.value(&mut cx);
    let callback = cx.argument::<JsFunction>(1)?.root(&mut cx);
    let channel = cx.channel();
    std::thread::spawn(move || {
        let socket = UdpSocket::bind("192.168.2.174:8000").expect("UdpSocket err");
        println!("{}", address);
        let _ = socket.connect(address.clone());
        channel.send(move |mut cx| {
            let callback = callback.clone(&mut cx).to_inner(&mut cx);
            let this = cx.undefined();
            loop {
                let mut buffer = [0u8; 1024];
                socket.recv_from(&mut buffer).expect("failed to receive");
                let data = std::str::from_utf8(&buffer).expect("failed to convertto String");
                println!("rust: {}", data);
                let args = vec![cx.string(data).upcast()];
                callback.call(&mut cx, this, args)?;
            }
            Ok(())
        });
    });
    Ok(cx.undefined())
}

JS:

import { parentPort } from 'worker_threads'
import ext from '../../rs-core/index.node'

function call(data) {
    parentPort?.postMessage(data)
    console.log(data)
}

parentPort?.on('message', data => {
    ext.parse_async(data, call)
})

The following is the message that is printed when the UDP server sends "test".

"192.168.2.174:8080"
rust: test
test                 // js print
rust: test
un def              // js print
@kjvalencik
Copy link
Member

This code is looping in the channel callback (main js thread) which is blocking the event loop. This might be the cause.

Can you try moving the loop outside of the channel.send callback?

@XiaoyuZhann
Copy link
Author

This code is looping in the channel callback (main js thread) which is blocking the event loop. This might be the cause.

Can you try moving the loop outside of the channel.send callback?

Thanks for the pointers, it works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants