Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include "WakeupEvent.h"
  2. #include "Simulator.h"
  3. #include "Node.h"
  4.  
  5. #include <iostream>
  6. #include <chrono>
  7. #include <random>
  8.  
  9.  
  10. Node::Node(Simulator * sim, int id) {
  11.     _simulator = sim;
  12.     _id=id;
  13. }
  14.  
  15.  
  16. float Node::getCrtTime() {
  17.     if (_simulator != nullptr)
  18.         return _simulator->getCrtTime();
  19.     else
  20.         return 0;
  21. }
  22.  
  23.  
  24. void Node::sleep(boost::coroutines2::coroutine<void>::push_type &contextSwitch, float deltat) {
  25.     // create the WakeupEvent
  26.     if (deltat <= 0)  // in case the deltat is invalid, do nothing
  27.         return;
  28.  
  29.     if (_simulator == nullptr)  // in case Node is not bound to a simulator, do nothing
  30.         return;
  31.  
  32.     Event * wu = new WakeupEvent(_id, _simulator, getCrtTime()+deltat);
  33.     _simulator->insertEvent(wu);
  34.  
  35.     // we now need to sleep so control flow switches to the simulator.
  36.     // When Simulator processes the packet and calls this node again,
  37.     // execution will resume from here.
  38.     contextSwitch();  
  39. }
  40.  
  41. // the CSMA algorithm should go in here
  42. // This is the MAIN function for the code that runs on the nodes of the network
  43. void Node::operator()(boost::coroutines2::coroutine<void>::push_type &contextSwitch) {
  44.     std::cout << "Node " << _id << " alive\n";
  45.  
  46.     unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  47.     std::minstd_rand0 generator (seed);  // minstd_rand0 is a standard linear_congruential_engine
  48.  
  49.     // run 5 iterations where we sleep a random amount of time units between 1 and 100.
  50.     for (int i=0; i<5; i++) {
  51.         // generate the random number
  52.         float sleeptime = generator() % 100;
  53.         std::cout << "Node " << _id << " crt time " << getCrtTime() << " sleeps for "
  54.                             << sleeptime << std::endl;
  55.         sleep(contextSwitch, sleeptime);
  56.         std::cout << "Wakeup! Node " << _id << " crt time " << getCrtTime() << std::endl;
  57.     }
  58.    
  59.     std::cout << "Node " << _id << " crt time " << getCrtTime() << " says good-bye!\n";
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement