Search code examples
clojure

will an atom defined locally visible to other threads?


I have to following code for automation, the function accepts a unique number, and kick off a firefox. I could kick off multiple threads, each thread with a unique x passing to the function, so the function will be executed concurrently. Then will the local atom current-page be visible to other threads? if visible, then the reset! could set the atom an expected value from another thread

(defn consumer-scanning-pages [x]
  (while true
    (let [driver (get-firefox x)
          current-page (atom 0)]
             ....
            (reset! current-page ..)
      )))

Solution

  • The atom will be visible to those threads you explicitly pass it to, to any further threads that those threads pass it to etc. It is no different in this respect to any other value that you may or may not pass around.

    "Passing the atom to a thread" can be as simple as referring to an in-scope local it is stored in within the body of a Clojure thread-launching form:

    (let [a (atom :foo)]
      ;; dereferencing the future object representing an off-thread computation
      @(future
         ;; dereferencing the atom on another thread
         @a))
    ;;= :foo
    

    Merely creating an atom doesn't make it available to code that it is not explicitly made available to, and this is also true of code that happens to run on the thread that originally created the atom. (Consider a function that creates an atom, but never stores it in any externally visible data structures and ultimately returns an unrelated value. The atom it creates will become eligible for GC when the function returns at the latest; it will not be visible to any other code, on the same or any other thread.) Again, this is also the case with all other values.