Skip to content

Instantly share code, notes, and snippets.

@ndemianc
Last active January 5, 2017 22:57
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 ndemianc/33166a292fa700c5ec483a6ac48c7882 to your computer and use it in GitHub Desktop.
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
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