Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active April 27, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagenorhynque/20ba1c76cb98cec5f01bfebad40b4e01 to your computer and use it in GitHub Desktop.
Save lagenorhynque/20ba1c76cb98cec5f01bfebad40b4e01 to your computer and use it in GitHub Desktop.
Sequential vs concurrent execution in Elixir & Clojure
(ns worker)
(defn random []
(inc (rand-int 100)))
(defn sleep [n]
(println (str "sleep(" n ") started."))
(Thread/sleep n)
(println (str "sleep(" n ") ended."))
(str "result-sleep(" n ")"))
(defn execute-sequentially []
(println "=== START ===")
(let [result (->> (range 1 (inc 100))
(map (fn [_] (random)))
(map (fn [t] (sleep t)))
doall)]
(println "=== END ===")
result))
(defn execute-concurrently []
(println "=== START ===")
(let [result (->> (range 1 (inc 100))
(map (fn [_] (random)))
(map (fn [t] (future (sleep t))))
(map (fn [d] (deref d)))
doall)]
(println "=== END ===")
result))
(defn execute-concurrently' []
(println "=== START ===")
(let [result (->> (range 1 (inc 100))
(map (fn [_] (random)))
(pmap (fn [t] (sleep t)))
doall)]
(println "=== END ===")
result))
defmodule Worker do
def random do
:rand.uniform(100)
end
def sleep(n) do
IO.puts "sleep(#{inspect n}) started."
:timer.sleep(n)
IO.puts "sleep(#{inspect n}) ended."
"result-sleep(#{inspect n})"
end
def execute_sequentially do
IO.puts "=== START ==="
result = 1..100
|> Enum.map(fn(_) -> random() end)
|> Enum.map(fn(t) -> sleep(t) end)
IO.puts "=== END ==="
result
end
def execute_concurrently do
IO.puts "=== START ==="
result = 1..100
|> Enum.map(fn(_) -> random() end)
|> Enum.map(fn(t) -> Task.async(Worker, :sleep, [t]) end)
|> Enum.map(fn(d) -> Task.await(d) end)
IO.puts "=== END ==="
result
end
end