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},
69 #state{cell_state=CellState
71 ,num_neighbors=NumNeighbors
74 ok = cast_all(Neighbors, {state_broadcast, GenID, CellState}),
75 {noreply, State#state{replies_pending=NumNeighbors, gen_id=GenID}};
78 %% If we receive 'state_broadcast' before we receive 'next_gen', throw it back
79 %% in the queue. (Took me a while to realize this, but sometimes it is
80 %% possible. The more there're cells, the more likely this is to happen.)
81 handle_cast({state_broadcast, ReceivedGenID, _NeighborState}=Msg,
82 #state{gen_id=GenID, name=Name}=State) when GenID =/= ReceivedGenID->
83 ok = gen_server:cast(Name, Msg),
87 %% Now that we can be sure that this request is for the current generation, we
89 handle_cast({state_broadcast, GenID, NeighborState},
92 ,replies_pending=Pending
94 ,live_neighbors=LiveNeighbors
97 NewPending = Pending - 1,
98 NewLiveNeighbors = LiveNeighbors + NeighborState,
100 NewState = State#state{replies_pending=NewPending
101 ,live_neighbors=NewLiveNeighbors
106 NewCellState = new_state(CellState, NewLiveNeighbors),
107 ok = life_time:report_state(CellID, GenID, NewCellState),
109 {noreply, NewState#state{live_neighbors=0
110 ,cell_state=NewCellState
119 handle_cast(_Msg, State) ->
123 handle_info(_Msg, State) ->
127 %% ============================================================================
129 %% ============================================================================
131 cast_all([], _) -> ok;
132 cast_all([Server | Servers], Msg) ->
133 ok = gen_server:cast(Server, Msg),
134 cast_all(Servers, Msg).
137 new_state(1, LiveNeighbors) when LiveNeighbors < 2 -> 0;
138 new_state(1, LiveNeighbors) when LiveNeighbors < 4 -> 1;
139 new_state(1, LiveNeighbors) when LiveNeighbors > 3 -> 0;
140 new_state(0, LiveNeighbors) when LiveNeighbors =:= 3 -> 1;
141 new_state(State, _LiveNeighbors) -> State.