Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <cstdlib>
- #include <chrono>
- #include <mutex>
- class Stock
- {
- private:
- mutable std::mutex m;
- double price;
- public:
- Stock(double startingPrice)
- {
- price = startingPrice;
- }
- double getPrice()
- {
- std::lock_guard<std::mutex> l(m);
- return price;
- }
- void setPrice(double Price)
- {
- std::lock_guard<std::mutex> l(m);
- price = Price;
- if(price < 0)
- price = 0.0;
- }
- };
- void priceRandom(Stock & stock)
- {
- for(;;)
- {
- stock.setPrice(stock.getPrice() + (std::rand()%200 - 100) / 100.0);
- std::this_thread::sleep_for(std::chrono::milliseconds(1));
- }
- }
- int main()
- {
- Stock stock(100);
- std::cout << "Hello world!\n";
- std::thread thread(priceRandom, std::ref(stock));
- for(int i = 0; i<100; i++)
- {
- std::cout << "Price of stock: " << stock.getPrice() << "\n";
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement