Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include<thread>
  3. #include<vector>
  4. #include<math.h>
  5. #include<string>
  6. #include<functional>
  7. #include<mutex>
  8.  
  9. std::mutex m;
  10. template<typename TFunc>
  11. void calcIntegral(TFunc& func, double a, double b, long long steps, double& result) {
  12. double localResult = 0;
  13. double step = (b - a) / steps;
  14. while (a <= b) {
  15. localResult += func(a) * step;
  16. a += step;
  17. }
  18. std::lock_guard<std::mutex> guard(m);
  19. result += localResult;
  20. }
  21.  
  22. /*mutex m;
  23. void Foo() {
  24. for (int i = 0; i < 100; i++) {
  25. m.lock();
  26. cout << "Thread: " << this_thread::get_id() << '\n';
  27. m.unlock();
  28. }
  29. }*/
  30.  
  31. int main()
  32. {
  33. /*vector<thread> threads;
  34.  
  35. for (int i = 0; i < 10; i++) {
  36. threads.emplace_back(Foo);
  37. }
  38.  
  39. for (auto& tr : threads) {
  40. if (tr.joinable())
  41. tr.join();
  42. }
  43. thread thread(Foo);
  44. Foo();
  45. thread.join();*/
  46.  
  47.  
  48. auto start = std::chrono::system_clock::now();
  49. std::function<double(double)> f{ [](double x) {return x; } };
  50. unsigned long long steps = 100000000ULL;
  51. unsigned threadCount = 8;
  52.  
  53. double result = 0;
  54.  
  55. std::vector<std::thread> threads;
  56.  
  57. for (int i = 0; i < threadCount; i++)
  58. {
  59. threads.emplace_back(calcIntegral<std::function<double(double)>>,
  60. std::ref(f),
  61. 1.0 / threadCount * i,
  62. 1.0 / threadCount * (i + 1),
  63. steps / threadCount,
  64. std::ref(result)
  65. );
  66. }
  67.  
  68. for (auto& tr : threads)
  69. {
  70. if (tr.joinable())
  71. tr.join();
  72. }
  73.  
  74. auto end = std::chrono::system_clock::now();
  75. std::chrono::duration<double, std::milli> diff = end - start;
  76.  
  77.  
  78. std::cout << "Time milisec = " << diff.count() << '\n'
  79. << "Result = " << result << '\n';
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement