一个进程中的多个 Ruby EventMachines:可能吗? [英] Multiple Ruby EventMachines in one process: possible?

查看:41
本文介绍了一个进程中的多个 Ruby EventMachines:可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Ruby 中运行多个 EventMachines - 有没有人有这方面的经验?(如果没有,我可能会写一个测试用例来自己做.敬请期待).

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).

让我们明确一点:我想自己实例化两个线程,并在两个线程中调用 EventMachine.run,所以我真的有两个反应器循环.

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.

原因是我正在使用 AMQP gem 编写异步消息总线,它使用 EventMachine.很好,但我想让它成为一个单独的模块化组件,可以在两个应用程序中使用:

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:

  • 有自己的阻塞 gui 循环(不能通过从 EventMachine 调用 tick 来模拟 - 它确实阻塞,并且它在 C 库中执行,所以我无法破解它).这个很简单——只需在它自己的线程中启动 EM,并以线程安全的方式在循环之间共享传入的消息;
  • 和另一个本身在反应器循环中运行的应用程序,我可能会与 AMQP 代码共享它(这对于线程安全问题很好 - 尽管我必须为上述问题解决这些问题)应用程序).这让我开始思考……我可以通过运行两个独立的 EventMachines 与上述应用程序共享消息总线代码吗?
  • 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?

有人有想法吗?

推荐答案

好的,深入研究 EM 的文档,我看到 EventMachine.run 的正文是这样开头的:

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 ...

这太棒了.看起来,如果您在多个线程中执行 EventMachine.run,它将在已经运行的反应器上调度第二台机器的定义 - 传递给run"的块.

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.

我喜欢这个图书馆.

这篇关于一个进程中的多个 Ruby EventMachines:可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆