Source

COS 520 Lamport 2 / Simulation.cpp

Full commit
#include <algorithm>

#include "Simulation.hpp"
#include "frand.hpp"
#include "Request.hpp"

using namespace std;

Simulation::Simulation(const unsigned int ProcessCount)
{
    Time = 0;
    majority = 2;  // based on knowing there are 3 total nodes
    highestRequest = 1;
    const float FailureProbability = 0.2f;
    const int Delta = 20;
    for(size_t i = 0; i < ProcessCount; ++i)
    {
        Processes.push_back(Process(i, this, ProcessCount, FailureProbability, Delta));
    }
}

void Simulation::tick()
{
  // display();

  // Iterate over Processes
  for(size_t i = 0; i < Processes.size(); ++i) {
    Processes[i].tick();
  }

  ++Time;
}


void Simulation::display()
{
  // Display basic info
  if (majorityPresent()) {
    cout << "MAJORITY\n";
  }
  else {
    cout << "SYSTEM DOWN\n";
  }
}


string Simulation::status()
{
  if (majorityPresent()) {
    return string("MAJORITY");
  }
  return string("System DOWN");
}


type::time Simulation::getTime()
{
    return Time;
}


void Simulation::sendMessage(const Message& MessageToSend)
{
  int pID = MessageToSend.getTo();
  Processes[pID].pushMessage(MessageToSend);
}


bool Simulation::majorityPresent()
{
  int upNodes = 0;
  for(size_t i = 0; i < Processes.size(); ++i) {
    if (Processes[i].isUp()) {
      upNodes++;
    }
  }
  if (upNodes >= majority) {
    return true;
  }
  return false;
}