Skip to content

Instantly share code, notes, and snippets.

@dgoeke
Created June 16, 2015 18:16
Show Gist options
  • Save dgoeke/2c8eb159cee7f019603f to your computer and use it in GitHub Desktop.
Save dgoeke/2c8eb159cee7f019603f to your computer and use it in GitHub Desktop.
Asynchronous processes and cancellation
(defn exec-cancellable
[cmd cancel]
(let [proc (sh/proc "sh" "-c" cmd)
exit (go (sh/exit-code proc))
[result ch] (alts!! [cancel exit])]
(go (if (= ch cancel)
(do
(sh/destroy proc)
:cancelled)
(if (zero? result) :success :failure)))))
(defn exec-group
[cmds]
(let [cancel (async/chan)
f #(exec-cancellable % cancel)
ch (async/merge (map f cmds))]
(loop [result true]
(let [val (<!! ch)]
(cond
(nil? val) result
(= val :failure) (do
(async/close! cancel)
(recur false))
:else (recur result))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment