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?
OK, digging into EM’s docs, I see the body for EventMachine.run starts with this:
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.