Skip to content

Instantly share code, notes, and snippets.

@UA3MQJ
Last active July 30, 2019 13:14
Show Gist options
  • Save UA3MQJ/d7572544d0922f0b9654c12ed3964c50 to your computer and use it in GitHub Desktop.
Save UA3MQJ/d7572544d0922f0b9654c12ed3964c50 to your computer and use it in GitHub Desktop.
‽Erlang/OTP 19 [erts-8.3] [64-bit] [smp:8:8] [async-threads:10]
Interactive Elixir (1.4.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> c("tst_gen.ex")
[TstGen]
iex(2)>
nil
iex(3)> {:ok, pid} = TstGen.start_link
{:ok, #PID<0.88.0>}
iex(4)>
nil
iex(5)> TstGen.test(pid)
18:48:27.508 [info] 1 fast_get -> GS
18:48:27.509 [info] 1 fast_result=1 <- GS
18:48:28.020 [info] 1 long_get -> GS
18:48:28.535 [info] 2 fast_get -> GS
18:48:28.535 [info] 2 fast_result=3 <- GS
18:48:29.035 [info] 2 long_get -> GS
18:48:29.035 [info] 1 long_result=2 <- GS
18:48:29.549 [info] 3 fast_get -> GS
18:48:29.550 [info] 3 fast_result=5 <- GS
18:48:30.049 [info] 3 long_get -> GS
18:48:30.049 [info] 2 long_result=4 <- GS
18:48:30.563 [info] 4 fast_get -> GS
18:48:30.563 [info] 4 fast_result=7 <- GS
18:48:31.063 [info] 4 long_get -> GS
:ok
18:48:31.063 [info] 3 long_result=6 <- GS
iex(6)>
18:48:32.077 [info] 4 long_result=8 <- GS
defmodule TstGen do
use GenServer
require Logger
def start_link do
GenServer.start_link(__MODULE__, 1)
end
def test(pid) do
for i <- [1, 2, 3, 4] do
:timer.sleep(500)
spawn(fn() ->
Logger.info "#{inspect i} fast_get -> GS"
result = GenServer.call(pid, :fast)
Logger.info "#{inspect i} fast_result=#{result} <- GS"
end)
:timer.sleep(500)
spawn(fn() ->
Logger.info "#{inspect i} long_get -> GS"
result = GenServer.call(pid, :long)
Logger.info "#{inspect i} long_result=#{result} <- GS"
end)
end
:ok
end
# SERVER
def init(state) do
{:ok, state}
end
def handle_call(:long, from, state) do
# start long process
spawn(fn() ->
:timer.sleep(1000)
:gen_server.reply(from, state)
end)
{:noreply, state+1}
end
def handle_call(:fast, _from, state) do
{:reply, state, state+1}
end
end
@UA3MQJ
Copy link
Author

UA3MQJ commented Sep 18, 2017

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment