Advertisement
Guest User

Untitled

a guest
Feb 25th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn wget []
  2.   (slurp "http://xx.yy"))
  3.  
  4. (defn show [s]
  5.   (print s)
  6.   (flush))
  7.  
  8. (defn snag-futures [n]
  9.   ;; Lazy q will be evaluated in chunks of 32 launching that many
  10.   ;; futures at a time:
  11.   (let [q (for [_ (range n)]
  12.             (do
  13.               (show "+")
  14.               (future (let [x (wget)]
  15.                         (show ".")
  16.                         x))))]
  17.     ;; mapv reterns a vec, not a lazy seq. Hm, launching all futures
  18.     ;; by (vec q) does not seem to help performance:
  19.     (mapv deref q)))
  20.  
  21. (defn snag-quotes [n]
  22.   (let [c (chan)]
  23.     ;; Posting to the channel here, each from a separate "thread". An
  24.     ;; exception that prevents a put would deadlock the reader down
  25.     ;; there:
  26.     (dotimes [n n]
  27.       (go (>! c (try
  28.                   (show "+")
  29.                   (let [x (wget)]
  30.                     (show ".")
  31.                     x)
  32.                   (catch Exception e
  33.                     ;; (str (.getMessage e))
  34.                     e)))))
  35.     ;; Reading n items from the channel here. The vec is delivered
  36.     ;; through a go-block result channel. There is also go-loop for
  37.     ;; this:
  38.     (<!! (go (loop [n n
  39.                     acc []]
  40.                (if (zero? n)
  41.                  acc
  42.                  (recur (dec n)
  43.                         (conj acc (<! c)))))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement