Created
January 24, 2020 13:36
-
-
Save nwjlyons/124194378a5e73f760d5e9dfc9e111c6 to your computer and use it in GitHub Desktop.
Playing with concurrency in Elixir
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 Math do | |
@doc """ | |
Calculate the square of a integer | |
This function simualtes an expensive operation by sleeping for x seconds | |
""" | |
def square(x) when is_integer(x) do | |
Process.sleep(x * 1_000) | |
x * x | |
end | |
end | |
defmodule English do | |
@doc """ | |
Pluralise a word | |
This function simulates and expensive operation by sleeping for the length of the word in seconds | |
eg. Given "bat" this function will sleep for three seconds | |
""" | |
def pluralise(word) when is_binary(word) do | |
Process.sleep(String.length(word) * 1_000) | |
word <> "s" | |
end | |
end | |
defmodule Concurrent do | |
@doc """ | |
Execute func for each element in the list concurrently | |
""" | |
def execute(list, func) when is_function(func) do | |
pid = self() | |
# Enumerate through indexed list and execute func in seperate process | |
Enum.each(Enum.with_index(list), fn {x, index} -> | |
# Perform work in seperate process | |
spawn fn -> | |
send pid, {index, func.(x)} | |
end | |
end) | |
collect(Enum.count(list)) | |
end | |
@doc """ | |
Collect results from workers via the mailbox | |
When the number of results is equal to the number of items in the original list return the results | |
Results need to be sorted and then the data structure | |
""" | |
defp collect(return_count, results \\ []) when is_integer(return_count) do | |
if Enum.count(results) >= return_count do | |
Enum.sort(results) | |
|> Enum.map(fn {_index, result} -> result end) | |
else | |
receive do | |
result -> collect(return_count, [result | results]) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment