diff --git a/term2/seminar01_thread/00problem_paralel_max.cpp b/term2/seminar01_thread/00problem_paralel_max.cpp new file mode 100644 index 0000000..59362b8 --- /dev/null +++ b/term2/seminar01_thread/00problem_paralel_max.cpp @@ -0,0 +1,100 @@ +/* + Задача: + + В данном примере написана функция getMax, которая находит максимум из чисел в векторе. + При этом вычисления проходят однопоточно. + + + Вам нужно написать функцию + + uint64_t getMaxPar(int n, const std::vector& v) + + которая будет делать то же самое, но только использовать для этого n потоков. +*/ + + +#include +#include +#include +#include +#include +#include +#include +#include +using std::cout, std::endl, std::size_t; +using namespace std::chrono_literals; + +uint64_t getMax(std::vector::const_iterator first, std::vector::const_iterator last) +{ + uint64_t res = *first; + for (; first != last; first++) + if (*first > res) + res = *first; + return res; +} + +uint64_t getMax(const std::vector& v) { + return getMax(v.begin(), v.end()); +} + +struct maxBlock { + void operator() (std::vector::const_iterator first, std::vector::const_iterator last, uint64_t& res) { + res = getMax(first, last); + } +}; + +uint64_t getMax(int n, const std::vector& v) { + std::vector results(n); + std::vector threads(n - 1); + + unsigned long const block_size = v.size() / n; + + auto block_start = v.begin(); + + for (int i = 0; i < n - 1; ++i) { + auto block_end = block_start; + std::advance(block_end, block_size); + threads[i] = std::thread(maxBlock(), + block_start, block_end, std::ref(results[i])); + block_start = block_end; + } + maxBlock() (block_start, v.end(), results[n - 1]); + + std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); + + return getMax(results); +} + + +int main() +{ + cout << "Generating numbers!" << endl; + std::vector numbers(5e8); + numbers[0] = 123456789; + for (size_t i = 1; i < numbers.size(); ++i) + { + numbers[i] = numbers[i - 1] * i + 1; + } + cout << "Numbers generated!" << endl; + + auto start = std::chrono::high_resolution_clock::now(); + + uint64_t m = getMax(numbers); + + auto end = std::chrono::high_resolution_clock::now(); + + cout << "Maximum = " << m << endl; + cout << "Time to calclulate max = " << std::chrono::duration_cast(end - start).count() + << " milliseconds." << endl; + + /* Parallel */ + start = std::chrono::high_resolution_clock::now(); + + m = getMax(4, numbers); + + end = std::chrono::high_resolution_clock::now(); + + cout << "Maximum = " << m << endl; + cout << "Time to calclulate max = " << std::chrono::duration_cast(end - start).count() + << " milliseconds." << endl; +}