Guest User

Untitled

a guest
May 2nd, 2014
204
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
  7.   "Run the body function number times in seperate threads.
  8.   Each thread will be listen to a barrier before executing his task."
  9.   [body number]
  10.   (let [start?          (atom false)
  11.         indices         (map list (iterate inc 0)) ; Returns (1 2 3..)
  12.         creators        (repeat number #(thread-factory % body start?)) ; Returns a list of partials
  13.         threadfunctions (map apply creators indices) ; Should return a list of functions
  14.         threads         (map #(Thread. %) threadfunctions)] ; Thread all the functions!
  15.  
  16.     (doseq [t threads] (.start t))
  17.     (reset! start? true)
  18.     (doseq [t threads] (.join t))
  19.     ))
  20.  
  21. (defn thread-factory
  22.   "Creates a thread which has a unique id."
  23.   [thread-id body start?]
  24.   (fn []
  25.     (loop [go? @start?]
  26.       (if go?
  27.         (body thread-id)
  28.         (recur @start?)))))
  29.  
  30. (defn run-with-barrier-looping
  31.   "Run the body function number times in seperate threads.
  32.   Each thread will be listen to a barrier before executing his task.
  33.   We return the atom that will stop these threads."
  34.   [body number]
  35.   (let [start?          (atom false)
  36.         stop            (atom false)
  37.         indices         (map list (iterate inc 0)) ; Returns (1 2 3..)
  38.         creators        (repeat number #(thread-factory-looping % body start? stop)) ; Returns a list of partials
  39.         threadfunctions (map apply creators indices) ; Should return a list of functions
  40.         threads         (map #(Thread. %) threadfunctions)] ; Thread all the functions!
  41.  
  42.     (doseq [t threads] (.start t))
  43.     (reset! start? true)
  44.     (reset! stop true) ;; works here!
  45.     (doseq [t threads] (.join t))
  46.     stop)) ;; stops working here..
  47.  
  48. (defn thread-factory-looping
  49.   "Creates a thread which has a unique id.
  50.   It loops each time."
  51.   [thread-id body start? stop]
  52.   (fn []
  53.     (loop [go? @start?]
  54.       (if go?
  55.         (do
  56.           (body thread-id)
  57.           (if (not @stop)
  58.             (do (println @stop)
  59.             (recur true))))
  60.         (recur @start?)))))
Advertisement
Add Comment
Please, Sign In to add comment