Advertisement
Guest User

Untitled

a guest
May 2nd, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns clj-project.barrier)
  2.  
  3. (declare thread-factory        )
  4. (declare thread-factory-looping)
  5.  
  6. (defn run-with-barrier-looping
  7.   "Run the body function number times in seperate threads.
  8.   Each thread will be listen to a barrier before executing his task.
  9.   We return the atom that will stop these threads."
  10.   [body number]
  11.   (let [start?          (atom false)
  12.         stop            (atom false)
  13.         indices         (map list (iterate inc 0)) ; Returns (1 2 3..)
  14.         creators        (repeat number #(thread-factory-looping % body start? stop)) ; Returns a list of partials
  15.         threadfunctions (map apply creators indices) ; Should return a list of functions
  16.         threads         (map #(Thread. %) threadfunctions)] ; Thread all the functions!
  17.  
  18.     (doseq [t threads] (.start t))
  19.     (reset! start? true)
  20.     (reset! stop true) ;; works here!
  21.     (doseq [t threads] (.join t))
  22.     stop)) ;; stops working here..
  23.  
  24. (defn thread-factory-looping
  25.   "Creates a thread which has a unique id.
  26.   It loops each time."
  27.   [thread-id body start? stop]
  28.   (fn []
  29.     (loop [go? @start?]
  30.       (if go?
  31.         (do
  32.           (body thread-id)
  33.           (if (not @stop)
  34.             (do (println @stop)
  35.             (recur true))))
  36.         (recur @start?)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement