fork download
  1. #include <iostream>
  2. #include <array>
  3. #include <numeric>
  4. #include <thread>
  5. #include <mutex>
  6. #include <stdexcept>
  7.  
  8. int TotalSum = 0;
  9. std::mutex mtx;
  10.  
  11. void computeEvenSum(const std::array<int, 20>& data) {
  12. int localSum = 0;
  13. for (int num : data) {
  14. if (num % 2 == 0) {
  15. localSum += num;
  16. }
  17. }
  18.  
  19. mtx.lock();
  20. TotalSum += localSum;
  21. mtx.unlock();
  22. }
  23.  
  24. void computeOddSum(const std::array<int, 20>& data) {
  25. int localSum = 0;
  26. for (int num : data) {
  27. if (num % 2 != 0) {
  28. localSum += num;
  29. }
  30. }
  31.  
  32. mtx.lock();
  33. TotalSum += localSum;
  34. mtx.unlock();
  35. }
  36.  
  37. int main() {
  38. try {
  39. std::array<int, 20> numbers;
  40. std::iota(numbers.begin(), numbers.end(), 1);
  41.  
  42. std::thread t1(computeEvenSum, std::ref(numbers));
  43. std::thread t2(computeOddSum, std::ref(numbers));
  44.  
  45. if (t1.joinable()) t1.join();
  46. if (t2.joinable()) t2.join();
  47.  
  48. std::cout << "Final value of TotalSum: " << TotalSum << std::endl;
  49. }
  50. catch (const std::runtime_error& e) {
  51. std::cerr << "Runtime error: " << e.what() << std::endl;
  52. }
  53. catch (const std::exception& e) {
  54. std::cerr << "Exception: " << e.what() << std::endl;
  55. }
  56. catch (...) {
  57. std::cerr << "Unknown exception caught." << std::endl;
  58. }
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Final value of TotalSum: 210