开发者

synchronize two ruby scripts on same computer

开发者 https://www.devze.com 2023-02-10 17:59 出处:网络
What\'s the best way to synchronize two ruby scripts running on the same computer? The开发者_JS百科 scripts will be started as separate processes from the shell.

What's the best way to synchronize two ruby scripts running on the same computer?

The开发者_JS百科 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.


Probably the easiest way of doing IPC in ruby is via drb and using Queue, which is located in thread:

require 'thread'
queue = Queue.new # provides blocking read

Note, when using drb, you'll want to have the following line near the top of your program:

Socket.do_not_reverse_lookup=true;

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 two Queue objects, one for the inbox and one for the outbox. The blocking read behavior of the Queue makes it easy to have the processes wait for each other. The Pipe is shared between the two processes via drb.

The server startup code might look like this:

require 'drb'
Socket.do_not_reverse_lookup=true;
uri = "druby://localhost:2250" # you can pick a port to communicate on
pipe = Pipe.new
DRb.start_service uri, pipe

The client startup code would look like:

require 'drb'
Socket.do_not_reverse_lookup=true;
uri = "druby://localhost:2250"
DRb.start_service
pipe = DRbObject.new nil, uri

Now the client and server can communicate via the Pipe object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号