在同一台计算机上同步两个 ruby 脚本
同步在同一台计算机上运行的两个 ruby 脚本的最佳方法是什么?
这些脚本将作为独立于 shell 的进程启动。
我希望脚本轮流运行。也就是说,我希望脚本 A 运行,向脚本 B 发送信号,然后等待脚本 B 的信号。当脚本 B 收到脚本 A 的信号时,它开始运行,当脚本 A 完成时向其发出信号,然后等待来自 A 的信号。基本上,我希望两个脚本交错运行。
实现这种同步的最佳方法是什么?
现在我能想到的就是创建一个文件作为信号(每个脚本忙循环等待创建文件)。是否还有其他更快/更简单/更安全的实现?
如果它影响答案,我在 OSX 上。
What's the best way to synchronize two ruby scripts running on the same computer?
The scripts will be started as separate processes from the shell.
I want the scripts to take turns running. That is, I want script A to run, send a signal to script B, then wait for a signal from script B. When script B gets the signal from script A, it starts running, signals script A when it is finished, and then waits for a signal from A. Basically, I want the two scripts to run interleaved.
What's the best way to implement this synchronization?
Right now all I can come up with is the creation of a file as the signal (each script busy loops waiting for a file to be created). Are there other implementations that are faster/easier/safer?
In case it affects the answer, I'm on OSX.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 ruby 中进行 IPC 的最简单方法可能是通过 drb 并使用
队列
,位于线程
中:请注意,使用 drb 时,您需要在程序顶部附近添加以下行:
没有它,程序运行速度会非常慢( 来源)。
为了解决问题中描述的具体问题,您可以创建一个
Pipe
类,它本质上只是两个Queue
对象,一个用于收件箱,一个用于发件箱。Queue
的阻塞读取行为使得进程很容易互相等待。Pipe
通过drb
在两个进程之间共享。服务器启动代码可能如下所示:
客户端启动代码可能如下所示:
现在客户端和服务器可以通过
Pipe
对象进行通信。Probably the easiest way of doing IPC in ruby is via drb and using
Queue
, which is located inthread
:Note, when using drb, you'll want to have the following line near the top of your program:
Without it, things just run extremely slowly (source).
To solve the specific problem described in the question, you can create a
Pipe
class, which essentially is just twoQueue
objects, one for the inbox and one for the outbox. The blocking read behavior of theQueue
makes it easy to have the processes wait for each other. ThePipe
is shared between the two processes viadrb
.The server startup code might look like this:
The client startup code would look like:
Now the client and server can communicate via the
Pipe
object.