Last active
January 17, 2019 13:42
-
-
Save yowchun93/6abd07635aa95429033a731bfc934cb5 to your computer and use it in GitHub Desktop.
Elixir server
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 DatabaseServer do | |
def start do | |
spawn(&loop/0) | |
end | |
# public API | |
def run_async(server_pid, query_def) do | |
send(server_pid, {:run_query, self, query_def}) | |
end | |
def get_result do | |
receive do | |
{ :query_result, result } -> result | |
after 5000 -> | |
{ :error, :timeout } | |
end | |
end | |
## the server handle by executing | |
## the query and sending query messsage back | |
defp loop do | |
receive do | |
## executes run_query and send the result back | |
{:run_query, caller, query_def} -> | |
send(caller, {:query_result, run_query(query_def)}) | |
end | |
loop | |
end | |
defp run_query(query_def) do | |
:timer.sleep(2000) | |
"#{query_def} result" | |
end | |
end | |
## creating a pool of elixir workers | |
pool = 1..100 |> Enum.map(fn(_) -> DatabaseServer.start end) | |
## randomly pick 5 workers to run | |
1..5 |> | |
Enum.each ( fn(query_def) -> | |
# selecting a random process | |
server_pid = Enum.at(pool, :random.uniform(100) -1 ) | |
DatabaseServer.run_async(server_pid, query_def) | |
end) | |
1..5 |> Enum.map (fn(_) -> DatabaseServer.get_result end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment