From e9cfa972d7ffd09584b678b42cb60bf50b8efa92 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 11 Jun 2021 11:24:08 +0800 Subject: import(life): ... --- .../operating-system-experiment/CMakeLists.txt | 2 + .../ParallelCalculationDemo.cpp | 73 ++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 works/life/operating-system-experiment/ParallelCalculationDemo.cpp (limited to 'works/life') diff --git a/works/life/operating-system-experiment/CMakeLists.txt b/works/life/operating-system-experiment/CMakeLists.txt index c8afc24..5671b4a 100644 --- a/works/life/operating-system-experiment/CMakeLists.txt +++ b/works/life/operating-system-experiment/CMakeLists.txt @@ -31,3 +31,5 @@ target_link_libraries(interlocked_avoid_data_race_demo PRIVATE cru_system) add_executable(semaphore_avoid_data_race_demo SemaphoreAvoidDataRaceDemo.cpp) target_link_libraries(semaphore_avoid_data_race_demo PRIVATE cru_system) +add_executable(parallel_calculation_demo ParallelCalculationDemo.cpp) +target_link_libraries(parallel_calculation_demo PRIVATE cru_system) diff --git a/works/life/operating-system-experiment/ParallelCalculationDemo.cpp b/works/life/operating-system-experiment/ParallelCalculationDemo.cpp new file mode 100644 index 0000000..31ff2bf --- /dev/null +++ b/works/life/operating-system-experiment/ParallelCalculationDemo.cpp @@ -0,0 +1,73 @@ +#include "Thread.h" + +#include + +const long long N = 1e9; + +int main(int argc, char **argv) { + int thread_number; + if (argc == 1) { + thread_number = 1; + } else if (argc == 2) { + thread_number = std::atoi(argv[1]); + if (thread_number <= 0) { + std::cerr << "Argument must be a positive integer.\n"; + } + } else { + std::cerr << "Too many arguments.\n"; + } + + std::cout << "Use " << thread_number << " threads to calculate sum of 1-" << N + << ".\n"; + + if (thread_number == 1) { + long long sum = 0; + for (long long i = 1; i <= 1e9; i++) { + sum += i; + } + std::cout << "Sum of 1-" << N << " is " << sum << '\n'; + } else { + std::vector threads(thread_number); + std::vector partial_sum(thread_number); + + long long step = N / thread_number; + + for (int i = 0; i < thread_number; i++) { + long long start = step * i; + long long end = step * (i + 1); + + long long &ps = partial_sum[i]; + + if (i == thread_number - 1) { + threads[i] = cru::Thread([&ps, start] { + long long sum = 0; + for (long long j = start; j <= 1e9; j++) { + sum += j; + } + ps = sum; + }); + } else { + threads[i] = cru::Thread([&ps, start, end] { + long long sum = 0; + for (int j = start; j < end; j++) { + sum += j; + } + ps = sum; + }); + } + } + + for (auto &thread : threads) { + thread.Join(); + } + + long long sum = 0; + for (auto ps : partial_sum) { + sum += ps; + } + + std::cout << "Sum of 1-" << N << " is " << sum << '\n'; + } + + return 0; +} -- cgit v1.2.3