comparison src/rlm/function_utils.clj @ 4:12d1367cf1aa

updating various utilities
author Robert McIntyre <rlm@mit.edu>
date Thu, 01 Mar 2012 05:47:23 -0700
parents c8e35134bf8e
children b8bbb0dbda7b
comparison
equal deleted inserted replaced
3:c8e35134bf8e 4:12d1367cf1aa
63 " 63 "
64 64
65 ) 65 )
66 66
67 67
68 (defn mix 68 (defn race
69 "Takes any number of mathematically equal functions with 69 "Takes any number of mathematically equal functions with
70 possibly different run-times and returns a function that 70 possibly different run-times and returns a function that
71 runs each in a separate thread, returns the result from 71 runs each in a separate thread, returns the result from
72 the first thread which finishes, and cancels the other threads." 72 the first thread which finishes, and cancels the other threads."
73 {:author "Robert McIntyre"} 73 {:author "Robert McIntyre"}
78 (future (deliver result (apply fun args))))) 78 (future (deliver result (apply fun args)))))
79 answer @result] 79 answer @result]
80 (dorun (map future-cancel futures)) 80 (dorun (map future-cancel futures))
81 answer)))) 81 answer))))
82 82
83 (defn mix-pred 83 (defn race-pred
84 "Takes any number of mathematically equal functions with 84 "Takes any number of mathematically equal functions with possibly
85 possibly different run-times and returns a function that 85 different run-times and returns a function that runs each in a
86 runs each in a separate thread, returns the result from 86 separate thread, and returns the first available result x for
87 the first thread which finishes, and cancels the other threads." 87 which (pred x) returns true (or not-valid, if (pred x) returns
88 {:author "Robert McIntyre"} 88 false on all the results). Cancels the other threads upon
89 ([pred & functions] 89 returning early."
90 {:author "Robert McIntyre"}
91 ([pred not-valid & functions]
90 (fn [& args] 92 (fn [& args]
91 (let [result (promise) 93 (let [result (promise)
92 futures (doall (for [fun functions] 94 latch (java.util.concurrent.CountDownLatch.
93 (let [answer (apply fun args)] 95 (count functions))
94 (if (pred answer) 96 failure-case (future (.await latch)
95 (future (deliver result (apply fun args))))))) 97 (deliver result not-valid))
98 futures
99 (doall
100 (cons failure-case
101 (for [fun functions]
102 (future
103 (let [answer? (apply fun args)]
104 (if (pred answer?)
105 (deliver result answer?)
106 (.countDown latch)))))))
96 answer @result] 107 answer @result]
97 (dorun (map future-cancel futures)) 108 (dorun (map future-cancel futures))
98 answer)))) 109 answer))))
99 110
100 111