Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include<thread>
- #include<vector>
- #include<math.h>
- #include<string>
- #include<functional>
- #include<mutex>
- std::mutex m;
- template<typename TFunc>
- void calcIntegral(TFunc& func, double a, double b, long long steps, double& result) {
- double localResult = 0;
- double step = (b - a) / steps;
- while (a <= b) {
- localResult += func(a) * step;
- a += step;
- }
- std::lock_guard<std::mutex> guard(m);
- result += localResult;
- }
- /*mutex m;
- void Foo() {
- for (int i = 0; i < 100; i++) {
- m.lock();
- cout << "Thread: " << this_thread::get_id() << '\n';
- m.unlock();
- }
- }*/
- int main()
- {
- /*vector<thread> threads;
- for (int i = 0; i < 10; i++) {
- threads.emplace_back(Foo);
- }
- for (auto& tr : threads) {
- if (tr.joinable())
- tr.join();
- }
- thread thread(Foo);
- Foo();
- thread.join();*/
- auto start = std::chrono::system_clock::now();
- std::function<double(double)> f{ [](double x) {return x; } };
- unsigned long long steps = 100000000ULL;
- unsigned threadCount = 8;
- double result = 0;
- std::vector<std::thread> threads;
- for (int i = 0; i < threadCount; i++)
- {
- threads.emplace_back(calcIntegral<std::function<double(double)>>,
- std::ref(f),
- 1.0 / threadCount * i,
- 1.0 / threadCount * (i + 1),
- steps / threadCount,
- std::ref(result)
- );
- }
- for (auto& tr : threads)
- {
- if (tr.joinable())
- tr.join();
- }
- auto end = std::chrono::system_clock::now();
- std::chrono::duration<double, std::milli> diff = end - start;
- std::cout << "Time milisec = " << diff.count() << '\n'
- << "Result = " << result << '\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement