On Thu, May 31, 2007 at 11:29:46AM +0900, Erwin Abbott wrote:
> I've been reading about DRb and one issue that I still have questions
> about is thread safety.  Every website I've come across uses very
> basic examples where the client never does anything that would modify
> the distributed object.

There's some examples which do this at
http://wiki.rubygarden.org/Ruby/page/show/DRbTutorial

Unfortunately Rubygarden is down more often than it's up (it's down as I
write this), but you can get a cached version through Google.

> For sake of discussion, let's say I'm writing an application that's
> some kind of database. Clients can add, delete, search, or modify
> records. How can this be written so clients can't step on each other,
> or block the whole database while perfoming and update on a single
> record?

Well, that's the general locking problem in a nutshell, and many books have
been written about this :-)

The solution will be domain-specific. The simplest solution is to serialise
all requests on the server side using a global mutex:

class DatabaseServer
  def initialize
    @mutex = Mutex.new
  end

  def add(r)
    @mutex.synchronize do
      # stuff
    end
  end

  def search(r)
    @mutex.synchronize do
      # stuff
    end
  end

  # etc
end

This is a reasonable approach if all the actions like add, search are
CPU-bound, because having concurrency here won't gain you anything.

If some of these actions can block on external I/O, then you might want to
have more concurrency. So you can look at having a shared read lock /
exclusive write lock kind of model; or you can push the problem downstream
(that is, write your app using some pre-existing thread-safe backend store,
and then just let multiple clients run your code concurrently)

B.