On Tue, Feb 22, 2011 at 10:37 PM, Andreas Kostler
<[email protected]> wrote:
> Hello all,
> How could one simulate a distributed atom, e.g. a ref that get updated 
> atomically and thus synchronised in two different processes.
> Has anyone thought about this in Clojure before?

Well, the simplest and most obvious thing is to wrap an atom in a
server. Run a thread that listens for some kind of network protocol
that tells it to perform deref, reset!, and compare-and-set!
operations on the atom. The corresponding client code consists of
three low-level functions that take an atom's name, a hostname, and
possibly a newval or both an oldval and a newval, and turns these into
the appropriate URI and uses it to cause the server running on
hostname to do a deref, reset!, or compare-and-set!. There'd also be
one higher-level function that implements remote swap! in terms of the
remote deref and compare-and-set!, something like

(loop []
  (let [oldv (remote-deref atom-addr)
        newv (f oldv)]
    (if (remote-compare-and-set! atom-addr oldv newv)
      newv
      (recur))))

No sleep/yield in the loop for the obvious reason: the remote-foos
perform blocking I/O and yield the CPU anyway so this won't hog the
processor. The loop either returns newv after an eventually-successful
remote-swap! or throws IOException, say if the host of the remote atom
becomes inaccessible.

You might also want the ability to command the creation of new atoms
on the host from the client, depending on your application.

Actually implementing the wire protocol is left as an exercise for the
reader. :)

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to