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

Ruby Concurrent Jscall failure #6

Open
adam429 opened this issue Jan 15, 2023 · 2 comments
Open

Ruby Concurrent Jscall failure #6

adam429 opened this issue Jan 15, 2023 · 2 comments

Comments

@adam429
Copy link
Contributor

adam429 commented Jan 15, 2023

When ruby code use Jscall, if the Ruby use multi-thread concurrent, the Jscall will be failed.


# define a function in js
Jscall.exec <<-CODE
    async function test(x)
    {
        await new Promise(r => setTimeout(r, 1000));
        return x
    }
CODE


# concurrent call in js
Jscall.exec <<-CODE
    async function parallel() {
        let p = []
        for (var i=1;i<=20;i++) {
            p.push(test(i))
        }
        return await Promise.all(p)
    }
CODE
ret1 = Jscall.parallel()

puts ret1.to_s
# output [1,2,3,4,5 ... , 20], ok


# non-concurrent call in ruby
ret2 = (1..20).to_a.map do |x|
    Jscall.test(x)
end
puts ret2.to_s
# output [1,2,3,4,5 ... , 20], ok



# concurrent call in ruby
ret3 = (1..20).to_a.map do |x|
    Thread.new do
        Jscall.test(x)
    end
end.map(&:value)

puts ret3.to_s
# except [1,2,3,4,5 ... , 20], but error```
@chibash
Copy link
Member

chibash commented Jan 15, 2023

Yes, that's true. The implementation of Jscall supports only single-threaded code in Ruby.

@adam429
Copy link
Contributor Author

adam429 commented Jan 16, 2023

Is there any possibility that we could support multi-threaded code from Ruby call (As the example I showed)

My thought was like this: in the send_command / send_reply data send from Ruby via PipeToJs, we add a session_id field to identify the session (The session_id is stay the same for multiple send_command / send_reply back-forth in one Ruby initiate Jscall.exec)

When the Ruby side Pipe receive the data in one thread (there could multiple threads initiate Jscall.exec with different session), the thread only fetch data in Pipe who has the same session_id. (Like a Messaging Queue, receiver only subscribe the specific topic)

For the JS side Pipe, it can process all session_id data in the same main_loop. But the process should be non-block via JS concurrency.

The Pipe between JS & Ruby is the shared resource. So multiple session can use the Pipe together with mutex and topic subscribe.

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