Guest User

Untitled

a guest
May 22nd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4.  
  5. class ThreadContainer
  6. {
  7.  
  8. std::thread t;
  9.  
  10. public:
  11. ThreadContainer(std::thread&& otherTh) : t(std::move(otherTh)) {}
  12.  
  13. ~ThreadContainer()
  14. {
  15. if (t.joinable())
  16. {
  17. t.join();
  18. }
  19. }
  20.  
  21. // to support moving
  22. ThreadContainer(ThreadContainer&&) = default;
  23. ThreadContainer& operator=(ThreadContainer&&) = default;
  24. };
  25.  
  26. void division(int a, int b)
  27. {
  28. if (b == 0)
  29. throw std::overflow_error("Divide by zero exception");
  30. std::cout << "Div " << float(a) / b << '\n';
  31. }
  32.  
  33. void addition(int a, int b)
  34. {
  35. std::this_thread::sleep_for(std::chrono::seconds(2));
  36. std::cout << "Add " << a + b << '\n';
  37. }
  38.  
  39. void doMaths()
  40. {
  41. ThreadContainer(std::thread(addition, 2, 3));
  42. ThreadContainer(std::thread(division, 2, 4));
  43. throw std::runtime_error("random error");
  44. /*
  45. std::thread t1(addition, 2, 3);
  46. std::thread t2(division, 2, 4);
  47.  
  48. throw std::runtime_error("random error");
  49. t1.join();
  50. t2.join();
  51. */
  52. }
  53.  
  54. int main()
  55. {
  56. doMaths();
  57. char ch;
  58. std::cin >> ch;
  59. }
Add Comment
Please, Sign In to add comment