Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Ruby EventMachines in one process: possible?

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?

like image 443
Matt Avatar asked Nov 23 '11 19:11

Matt


2 Answers

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.

like image 167
Matt Avatar answered Sep 25 '22 16:09

Matt


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
like image 37
Schmurfy Avatar answered Sep 23 '22 16:09

Schmurfy