# ant = Ant.start_link # Ant.show_food(ant) # Ant.find_food(ant, 3) # Ant.show_food(ant) # defmodule Ant do # use GenServer # # # Client API # def start_link(name) do # IO.puts "client start_link" # IO.inspect name # IO.puts "start_link" # {:ok, state} = GenServer.start_link(__MODULE__, name, name: name) # state # end # # def find_food(state, quantity) when is_integer(quantity) do # GenServer.cast(state, {:find_food, quantity}) # end # # def show_food(state) do # GenServer.call(state, {:show_food}) # end # # # Server API # def init(state) do # IO.puts "server init" # {:ok, state} # end # # def handle_cast({:find_food, quantity}, state) do # hunt_duration = 1000 + :rand.uniform(5000) # Process.send_after(self(), {:update_food, quantity}, hunt_duration) # {:noreply, state} # end # # def handle_call({:show_food}, _from, state) do # {:reply, state, state} # end # # def handle_info({:update_food, quantity}, state) do # {:noreply, state + quantity} # end # end defmodule Ant do def start_link do Agent.start_link(fn -> 0 end) end def show_food(ant) do Agent.get(ant, fn count -> count end) end def find_food(ant) do hunt_duration = 1000 + :rand.uniform(10000) :timer.sleep(hunt_duration) Agent.update(ant, fn count -> count + 1 end) end end