Advertisement
ifinox

Untitled

Sep 8th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <cstdlib>
  4. #include <chrono>
  5. #include <mutex>
  6.  
  7. #define NanoSeconds 10
  8.  
  9. class Stock
  10. {
  11. private:
  12.     double price;
  13.     int changes;
  14. public:
  15.     Stock(double startingPrice)
  16.     {
  17.         changes = 0;
  18.         price = startingPrice;
  19.     }
  20.     double getPrice()
  21.     {
  22.         return price;
  23.     }
  24.     void setPrice(double Price)
  25.     {
  26.  
  27.         price = Price;
  28.         if(price < 0)
  29.             price = 0.0;
  30.         changes++;
  31.     }
  32.     int getChanges()
  33.     {
  34.         return changes;
  35.     }
  36. };
  37.  
  38. void priceRandom(Stock & stock)
  39. {
  40.     for(;;)
  41.     {
  42.         stock.setPrice(stock.getPrice() + (std::rand()%200 - 100) / 100.0);
  43.         std::this_thread::sleep_for(std::chrono::nanoseconds(NanoSeconds));
  44.     }
  45. }
  46.  
  47. int main()
  48. {
  49.     Stock stock(100);
  50.     std::cout << "Hello world!\n";
  51.  
  52.     std::thread thread(priceRandom, std::ref(stock));
  53.    
  54.     auto start = std::chrono::system_clock::now();
  55.  
  56.     for(;;)
  57.     {
  58.         int changes = stock.getChanges();
  59.         std::cout << "Price of stock: " << stock.getPrice() << "\tchanges: " << changes << "\n";
  60.         std::this_thread::sleep_for(std::chrono::milliseconds(10));
  61.         if (changes > 10000)
  62.             break;
  63.     }
  64.  
  65.     auto end = std::chrono::system_clock::now();
  66.     auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  67.     std::cout << "Thread sleep = " << NanoSeconds << "ns\n" << elapsed.count() << "ms" << '\n';
  68.  
  69.     thread.join();
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement