Last active
January 5, 2017 22:57
-
-
Save ndemianc/33166a292fa700c5ec483a6ac48c7882 to your computer and use it in GitHub Desktop.
Small linked task, that can run on the multicore processor, and save a state inside Map like key-value store in Elixir
This file contains hidden or 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 Project do | |
@moduledoc """ | |
This module includes example code of the Elixir linked tasks based on the Elixir linked processes. | |
""" | |
@doc """ | |
Create new task. | |
Returns `{:ok, pid}` | |
## Examples | |
iex> {:ok, pid} = Project.start_link | |
{:ok, #PID<0.139.0>} | |
iex> send pid, {:put, :message, "Hello World"} | |
{:put, :message, "Hello World"} | |
iex> send pid, {:get, :message, self()} | |
{:get, :message, #PID<0.137.0>} | |
iex> flush | |
"Hello World" | |
:ok | |
""" | |
def start_link do | |
Task.start_link(fn -> | |
loop(%{}) | |
end) | |
end | |
defp loop(map) do | |
receive do | |
{:get, key, caller} -> | |
send caller, Map.get(map, key) | |
loop(map) | |
{:put, key, value} -> | |
loop(Map.put(map, key, value)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment