private void LeaderElection() { Receive <Init>(x => { Election msg = new Election(id, 0, 0); Console.WriteLine("[Actor " + id + "] Initializing... sending: " + msg); leftNeighbour.Tell(msg); rightNeighbour.Tell(msg); } ); Receive <Election>(x => x.Id < id, x => Console.WriteLine("[Actor " + id + "] Ignoring message: " + x)); Receive <Election>(x => x.Id > id, x => HandleReceivedLargerId(x)); Receive <Election>(x => x.Id == id, x => Winner(x)); Receive <Elected>(x => HandleElected(x)); Receive <Reply>(x => x.Id != id, x => ForwardReply(x)); Receive <Reply>(x => HandleSameIdReply(x)); }
private void HandleSameIdReply(Reply x) { if (!gotReplyFrom.ContainsKey(Sender.Path.ToString())) { gotReplyFrom.Add(Sender.Path.ToString(), 0); } string leftNeighbourPath = leftNeighbour.Anchor.Path + leftNeighbour.Path.Select(y => y.ToString()) .Aggregate((z, y) => z + "/" + y); string rightNeighbourPath = rightNeighbour.Anchor.Path + rightNeighbour.Path.Select(y => y.ToString()) .Aggregate((z, y) => z + "/" + y); gotReplyFrom[Sender.Path.ToString()]++; if (!gotReplyFrom.ContainsKey(leftNeighbourPath)) { gotReplyFrom.Add(leftNeighbourPath, 0); } if (!gotReplyFrom.ContainsKey(rightNeighbourPath)) { gotReplyFrom.Add(rightNeighbourPath, 0); } if (gotReplyFrom[leftNeighbourPath] > 0 && gotReplyFrom[rightNeighbourPath] > 0) { Console.WriteLine("[Actor " + id + "] Propagating election... New phase: " + (x.CurrentPhase + 1)); gotReplyFrom[leftNeighbourPath] = 0; gotReplyFrom[rightNeighbourPath] = 0; Election newMsg = new Election(x.Id, x.CurrentPhase + 1, 1); leftNeighbour.Tell(newMsg); rightNeighbour.Tell(newMsg); } }
private void ForwardElection(Election x) { Forward(new Election(x.Id, x.CurrentPhase, x.Hop + 1)); }
private void Winner(Election x) { leaderId = x.Id; rightNeighbour.Tell(new Elected(id)); }