Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <chrono>
- #include <vector>
- #include <atomic>
- int main()
- {
- int *mas;
- auto maxThreads = std::thread::hardware_concurrency();
- std::vector<std::thread *> threads(maxThreads);
- std::vector<int> summs(maxThreads);
- std::vector<std::atomic<int>> status(maxThreads);
- srand(time(0));
- size_t masSize = rand();
- std::cout << "Creating mas[" << masSize << "]..." << std::endl;
- mas = new int[masSize];
- for (size_t i = 0; i < masSize; ++i)
- mas[i] = rand();
- std::cout << "done." << std::endl;
- auto parallelSummCalc = [&mas, &masSize](size_t start, int step, int &summ, std::atomic<int> & status){
- if (start > masSize)
- return;
- for (size_t i = start; i < masSize; i += step)
- summ += mas[i];
- status = 1;
- };
- auto singleStart = std::chrono::system_clock::now();
- int summ = 0;
- std::atomic<int> s;
- auto t = new std::thread(parallelSummCalc, 0, 1, std::ref(summ), std::ref(s));
- // t->join();
- for (;;){
- if (s == 1)
- break;
- }
- std::cout << "Single time: " << (std::chrono::system_clock::now() - singleStart).count() << std::endl;
- std::cout << "Single value:" << summ << std::endl;
- t->join();
- delete t;
- auto dynamicStart = std::chrono::system_clock::now();
- for (size_t i = 0; i < maxThreads; ++i)
- threads.at(i) = new std::thread(parallelSummCalc, i, maxThreads, std::ref(summs.at(i)), std::ref(status.at(i)));
- // for (auto &thread : threads)
- // thread->join();
- summ = 0;
- // for (size_t i = 0; i < maxThreads; ++i){
- // summ += summs.at(i);
- // summs.at(i) = 0;
- // }
- for (;;){
- bool next = false;
- for (size_t i = 0; i < maxThreads; ++i){
- if (status.at(i) == 1){
- status.at(i) = 2;
- next = true;
- summ += summs.at(i);
- } else if (status.at(i) == 0)
- next = true;
- }
- if (!next)
- break;
- }
- std::cout << "Dynamic(" << maxThreads << ") time: " << (std::chrono::system_clock::now() - dynamicStart).count() << std::endl;
- std::cout << "Dynamic(" << maxThreads << ") value:" << summ << std::endl;
- for (auto &thread : threads){
- thread->join();
- delete thread;
- }
- threads.clear();
- delete[] mas;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement