2 -behaviour(gen_server).
6 -export([start_link/1]).
18 -record(state, {cell_id :: integer()
21 ,neighbors :: list(atom())
22 ,live_neighbors :: integer()
23 ,num_neighbors :: integer()
24 ,replies_pending :: integer()
29 %% ============================================================================
31 %% ============================================================================
33 start_link({_, Name, _}=Datum) ->
34 ServerName = {local, Name},
37 gen_server:start_link(ServerName, ?MODULE, Args, Opts).
40 %% ============================================================================
42 %% ============================================================================
44 init([{CellID, Name, NeighborNames}]) ->
45 State = #state{cell_id = CellID
47 ,cell_state = crypto:rand_uniform(0, 2)
48 ,neighbors = NeighborNames
49 ,num_neighbors = length(NeighborNames)
56 terminate(_Reason, State) ->
60 code_change(_Old, State, _Other) ->
64 handle_call(_Msg, _From, State) ->
68 handle_cast({next_gen, GenID},
71 ,num_neighbors=NumNeighbors
74 ok = cast_all(Neighbors, {request_state, GenID, Name}),
75 {noreply, State#state{replies_pending=NumNeighbors, gen_id=GenID}};
77 %% If we receive this before we receive next_gen, throw it back in the queue.
78 %% (Took me a while to realize this, but sometimes it is possible. The more
79 %% there're cells, the more likely this is to happen.)
80 handle_cast({request_state, GenID, _Requester}=Msg,
83 }=State) when GenID =/= MyGenID->
85 gen_server:cast(Name, Msg),
88 %% Now that we can be sure that this request is for the current generation, we
90 handle_cast({request_state, GenID, Requester},
93 }=State) when GenID =:= MyGenID->
95 ok = gen_server:cast(Requester, {response_state, MyGenID, CellState}),
98 handle_cast({response_state, GenID, NeighborState},
101 ,replies_pending=Pending
102 ,cell_state=CellState
103 ,live_neighbors=LiveNeighbors
106 NewPending = Pending - 1,
107 NewLiveNeighbors = LiveNeighbors + NeighborState,
109 NewState = State#state{replies_pending=NewPending
110 ,live_neighbors=NewLiveNeighbors
115 NewCellState = new_state(CellState, NewLiveNeighbors),
116 ok = life_time:report_state(CellID, GenID, NewCellState),
118 {noreply, NewState#state{live_neighbors=0
119 ,cell_state=NewCellState
127 handle_cast(_Msg, State) ->
131 handle_info(_Msg, State) ->
135 %% ============================================================================
137 %% ============================================================================
139 cast_all([], _) -> ok;
140 cast_all([Server | Servers], Msg) ->
141 ok = gen_server:cast(Server, Msg),
142 cast_all(Servers, Msg).
145 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
146 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
147 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
148 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
149 new_state(State, _LiveNeighbors) -> State.