Advertisement
ifinox

Untitled

Sep 8th, 2017
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <cstdlib>
  4. #include <chrono>
  5. #include <mutex>
  6.  
  7. class Stock
  8. {
  9. private:
  10.     mutable std::mutex m;
  11.     double price;
  12. public:
  13.     Stock(double startingPrice)
  14.     {
  15.         price = startingPrice;
  16.     }
  17.     double getPrice()
  18.     {
  19.         std::lock_guard<std::mutex> l(m);
  20.         return price;
  21.     }
  22.     void setPrice(double Price)
  23.     {
  24.         std::lock_guard<std::mutex> l(m);
  25.  
  26.         price = Price;
  27.         if(price < 0)
  28.             price = 0.0;
  29.     }
  30. };
  31.  
  32. void priceRandom(Stock & stock)
  33. {
  34.     for(;;)
  35.     {
  36.         stock.setPrice(stock.getPrice() + (std::rand()%200 - 100) / 100.0);
  37.         std::this_thread::sleep_for(std::chrono::milliseconds(1));
  38.     }
  39. }
  40.  
  41. int main()
  42. {
  43.     Stock stock(100);
  44.     std::cout << "Hello world!\n";
  45.  
  46.     std::thread thread(priceRandom, std::ref(stock));
  47.    
  48.     for(int i = 0; i<100; i++)
  49.     {
  50.         std::cout << "Price of stock: " << stock.getPrice() << "\n";
  51.         std::this_thread::sleep_for(std::chrono::milliseconds(10));
  52.     }
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement