Multiple Ruby EventMachines in one process: possible?

冷暖自知 提交于 2019-12-09 18:10:09

问题


I have a situation where I want to run multiple EventMachines in Ruby - does anyone have experience with this? (I may write a test case to do it myself if not. Stay tuned).

Let's be clear: I want to instantiate two threads myself, and call EventMachine.run in both threads, so I really have two reactor loops.

The reason why is that I'm writing an asynchronous message bus with the AMQP gem, which uses EventMachine. That's fine, but I want to make that a separate, modular component that can be used within two applications:

  • one that has its own blocking gui loop (that cannot be simulated by calling tick from EventMachine - it really blocks, and it does it in a C library, so I can't hack it). This one is simple - just start EM in its own thread, and share the incoming messages between loops in a thread-safe manner;
  • and another application that itself is running in a reactor loop, which I could potentially share with the AMQP code (which is nice for thread safety issues - though I have to address them anyway for the above app). This is the one that got me thinking... could I share the message bus code with the above app by running two separate EventMachines?

Anybody have thoughts?


回答1:


OK, digging into EM's docs, I see the body for EventMachine.run starts with this:

240:     if reactor_running?
241:       (b = blk || block) and b.call # next_tick(b)
242:     else
         ... start the reactor ...

This is awesome. It looks like, if you do EventMachine.run in multiple threads, it will schedule the second machine's definition - the block passed to "run" - on the reactor that is already running.

I love this library.




回答2:


You answered yourself but I wanted to add my 2 cents without the horrible styling of comments.

# this will start the eventmachine reactor
EM::run do

  # do something

  # this will do nothing and the block passed to it will
  # just be executed directly
  EM::run do
    # do something else
  end

end


来源:https://stackoverflow.com/questions/8247691/multiple-ruby-eventmachines-in-one-process-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!