fork download
  1. #include <mutex>
  2. #include <thread>
  3. #include <iostream>
  4.  
  5. struct Point
  6. {
  7. public:
  8. void getXY(double& x, double& y) const;
  9. void setXY(double x, double y);
  10. private:
  11. double xcoord;
  12. double ycoord;
  13. mutable std::mutex m;
  14. };
  15.  
  16.  
  17. void Point::getXY(double& x, double& y) const
  18. {
  19. std::lock_guard<std::mutex> lg(m);
  20. x = xcoord;
  21. y = ycoord;
  22. }
  23.  
  24. void Point::setXY(double x, double y)
  25. {
  26. std::lock_guard<std::mutex> lg(m);
  27. xcoord = x;
  28. ycoord = y;
  29. }
  30.  
  31. void printPoint(const Point &p)
  32. {
  33. double x, y;
  34. p.getXY(x, y);
  35. std::cout << "X: " << x
  36. << ", Y: " << y << std::endl;
  37. }
  38.  
  39. void increasePoint(Point &p)
  40. {
  41. double x, y;
  42. p.getXY(x, y);
  43. p.setXY(x * 2, y * 2);
  44. }
  45.  
  46. int main()
  47. {
  48. Point p;
  49. p.setXY(1.1, -1.1);
  50.  
  51. std::thread t1(printPoint, std::ref(p));
  52. std::thread t2(increasePoint, std::ref(p));
  53. std::thread t3(increasePoint, std::ref(p));
  54. std::thread t4(printPoint, std::ref(p));
  55.  
  56. t1.join(); t2.join(); t3.join(); t4.join();
  57. return 0;
  58. }
Success #stdin #stdout 0s 36240KB
stdin
Standard input is empty
stdout
X: 1.1, Y: -1.1
X: 4.4, Y: -4.4