Last active
April 27, 2019 15:51
-
-
Save lagenorhynque/20ba1c76cb98cec5f01bfebad40b4e01 to your computer and use it in GitHub Desktop.
Sequential vs concurrent execution in Elixir & Clojure
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 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)) |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cf. 挑戦! Elixirによる並行・分散アプリケーションの作り方【第二言語としてのElixir】 - Elixirの並行処理に挑戦