Created
October 11, 2018 16:50
-
-
Save divs1210/f1f050bbdaf045b1f43bbb346267e69c to your computer and use it in GitHub Desktop.
Clojure fork-join example
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 fork-join-recur | |
(:import [java.util.concurrent ForkJoinPool | |
ForkJoinWorkerThread ForkJoinTask RecursiveTask])) | |
;; API | |
;; === | |
(def ^:dynamic ^ForkJoinPool *pool* (ForkJoinPool/commonPool)) | |
(defmacro fork [& body] | |
`(let [^ForkJoinTask task# (proxy [RecursiveTask] [] | |
(compute [] | |
(do ~@body)))] | |
(if (ForkJoinTask/inForkJoinPool) | |
(.fork task#) | |
(.execute *pool* task#)) | |
task#)) | |
(defn join [^ForkJoinTask task] | |
(.join task)) | |
;; Test | |
;; ==== | |
(defn rec:factorial [n] | |
(fork | |
(if (< n 2) | |
1 | |
(*' n (join (rec:factorial (dec n))))))) | |
(defn factorial [n] | |
(join (rec:factorial n))) | |
#_( | |
(factorial 5) ;; => 120 | |
(factorial 5000) ;; => StackOverflow! | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment