Sync two ruby ​​scripts on one computer

What is the best way to synchronize two ruby ​​scripts running on the same computer?

Scripts will run as separate processes from the shell.

I want scripts to take turns. That is, I want to run script A, send a signal to script B, and then wait for a signal from script B. When script B receives a signal from script A, it starts to work, script A signals when it is finished, and then waits for a signal from A Basically, I want the two scripts to perform interleaving.

What is the best way to implement this synchronization?

Currently, all I can think of is creating a file as a signal (each script busy loop), waiting for the file to be created). Are there other implementations that are faster / easier / safer?

In case this affects the answer, I am in OSX.

+3
source share
1 answer

Probably the easiest way to make IPC in ruby ​​is drb and use Queuewhich is in thread:

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

Note that when using drb, you want to have the following line at the top of your program:

Socket.do_not_reverse_lookup=true;

Without this, everything happens very slowly ( source ).

To solve the specific problem described in the question, you can create a class Pipethat essentially consists of only two objects Queue, one for incoming and one for outgoing. Read lock behavior Queuesimplifies the process of waiting for each other. Pipeshared between two processes through drb.

:

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

:

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

Pipe.

+2

Source: https://habr.com/ru/post/1791799/


All Articles