fork download
  1. #include <thread>
  2. #include <iostream>
  3. #include <mutex>
  4.  
  5. std::once_flag flag;
  6. const size_t arraySize = 1000;
  7. int array[arraySize];
  8. void fillWithRandomNumbers()
  9. {
  10. std::srand(time(0));
  11. for (size_t index = 0; index < arraySize; ++index)
  12. array[index] = (rand() % 999 + 1);
  13. }
  14.  
  15. void countEvenAndOddNumbers(int counter[2])
  16. {
  17. std::call_once(flag, fillWithRandomNumbers);
  18.  
  19. counter[0] = 0;
  20. counter[1] = 0;
  21.  
  22. for (size_t index = 0; index < arraySize; ++index)
  23. ++counter[array[index] & 1];
  24. }
  25.  
  26.  
  27. int summ(int num)
  28. {
  29. int sum = 0;
  30. while (num != 0)
  31. {
  32. sum += num % 10;
  33. num /= 10;
  34. }
  35. return sum;
  36. }
  37. void findDivisibleByThree(int* result, int* counter)
  38. {
  39. std::call_once(flag, fillWithRandomNumbers);
  40. *counter = 0;
  41. for (size_t index = 0; index < arraySize; ++index)
  42. {
  43. if ((summ(index) % 3) == 0)
  44. {
  45. result[*counter] = array[index];
  46. ++*counter;
  47. }
  48. }
  49. }
  50.  
  51. void countDivisibleByFiveOrSeven(int* count)
  52. {
  53. std::call_once(flag, fillWithRandomNumbers);
  54. *count = 0;
  55. for (size_t index = 0; index < arraySize; ++index)
  56. {
  57. if ((((array[index] % 5) == 0)) || ((array[index] % 7) == 0))
  58. ++*count;
  59. }
  60. }
  61.  
  62. int main()
  63. {
  64. int array[arraySize];
  65. int counter[2];
  66. int count = 0;
  67. int cou = 0;
  68. std::thread t1(countEvenAndOddNumbers, counter);
  69. std::thread t2(findDivisibleByThree , array, &cou);
  70. std::thread t3(countDivisibleByFiveOrSeven, &count);
  71. t1.join();
  72. t2.join();
  73. t3.join();
  74.  
  75. std::cout << "Even- " << counter[0] << "\n";
  76. std::cout << "Odd- " << counter[1] << "\n";
  77. std::cout << "EntireThree- " << cou << "\n";
  78. std::cout << "EntireFiveOrSeven- " << count << "\n";
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0s 21400KB
stdin
Standard input is empty
stdout
Even- 503
Odd- 497
EntireThree- 334
EntireFiveOrSeven- 334