Threads, DRb.thread.join and keeping a server alive
A dRuby server runs in a background thread, so the script must wait on it with DRb.thread.join. Also: why front objects must be thread-safe.
Updated
DRb.start_service returns immediately. The server it starts runs in a background thread, and a Ruby process exits when its main thread finishes, whatever other threads are doing. So a server script must end by waiting on the server thread, and the usual way is DRb.thread.join.
The exit problem
require 'drb/drb'
DRb.start_service('druby://localhost:8787', Object.new)
# The script ends here, and the server ends with it.
Add one line and it stays up until you stop it:
require 'drb/drb'
DRb.start_service('druby://localhost:8787', Object.new)
DRb.thread.join
DRb.thread returns the thread of the primary server, the one started by DRb.start_service. join blocks the main thread until that thread ends.
Stopping cleanly
DRb.stop_service stops the primary server, which also lets a waiting DRb.thread.join return.
require 'drb/drb'
DRb.start_service('druby://localhost:8787', Object.new)
trap('INT') { Thread.new { DRb.stop_service } }
DRb.thread.join
puts 'Stopped.'
Pressing Ctrl-C now stops the service and the script prints Stopped. on its way out. The work is done in a new thread because a signal handler is a restricted context where taking locks is not allowed.
When you do not need join
- A client that makes its calls and finishes does not need it.
- A program that already has a long-running main loop, such as a GUI or another server, does not need it. dRuby keeps serving in the background while the main thread does its own work.
- A client that sits waiting for callbacks does need it, or some other way to keep the main thread alive.
Calls run concurrently
dRuby handles incoming calls in separate threads, so two clients can be inside methods of the same front object at the same moment. Any state the object changes must be protected, exactly as in any other threaded Ruby program.
require 'drb/drb'
class Counter
def initialize
@count = 0
@lock = Mutex.new
end
def increment
@lock.synchronize { @count += 1 }
end
end
DRb.start_service('druby://localhost:8787', Counter.new)
DRb.thread.join
Without the Mutex, two overlapping calls could read the same value of @count and one increment would be lost.
Slow methods
Because each call has its own thread, a slow method does not stop the server from accepting other calls. It does make its own caller wait: a remote call blocks in the client until the result comes back. If a caller should not wait, have the method put the work on a Queue that a worker thread drains and return straight away, or hand the job to a Rinda tuple space.
Exceptions
An exception raised inside a remote method does not bring the server down. It is sent back and raised in the calling process, and the server carries on with other requests.