Created
December 8, 2016 21:00
-
-
Save bhurlow/6a1ea489278ee188990597f7b04765cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns scraper.concurrent | |
(:import [java.util.concurrent | |
ExecutorService | |
ExecutorCompletionService | |
Executors | |
CompletionService Future])) | |
(defn prln [& more] | |
(.write | |
*out* | |
(str (clojure.string/join " " more) "\n")) | |
(flush)) | |
(defn take-seq | |
"accepts an ExecutorCompletionService, and returns | |
a lazy seq of values taken from the service" | |
[worker] | |
(lazy-seq | |
(let [result (.take worker)] | |
(cons (.get result) | |
(take-seq worker))))) | |
(defn cmap | |
"executes function f against coll in thread pool of size threads" | |
[f threads coll] | |
(let [pool (Executors/newFixedThreadPool threads) | |
worker (ExecutorCompletionService. pool)] | |
(doseq [x coll] (.submit worker #(f x))) | |
(take (count coll) (take-seq worker)))) | |
;; example for cmap | |
(defn go [] | |
(cmap | |
(fn [x] | |
(Thread/sleep (rand-int 1000)) | |
(prln "RUN" x) | |
(str "DID" x)) | |
;; 5 threads | |
5 | |
;; 20 item coll | |
(range 20))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment