diff options
author | Yuqian Yang <crupest@crupest.life> | 2025-02-28 23:13:39 +0800 |
---|---|---|
committer | Yuqian Yang <crupest@crupest.life> | 2025-02-28 23:13:39 +0800 |
commit | dc1f0c4c0096013799416664894c5194dc7e1f52 (patch) | |
tree | 2f5d235f778cd720f4c39ec3e56b77ba6d99f375 /works/life/operating-system-experiment/ParallelCalculationDemo.cpp | |
parent | 7299d424d90b1effb6db69e3476ddd5af72eeba4 (diff) | |
download | crupest-dc1f0c4c0096013799416664894c5194dc7e1f52.tar.gz crupest-dc1f0c4c0096013799416664894c5194dc7e1f52.tar.bz2 crupest-dc1f0c4c0096013799416664894c5194dc7e1f52.zip |
chore(store): move everything to store.
Diffstat (limited to 'works/life/operating-system-experiment/ParallelCalculationDemo.cpp')
-rw-r--r-- | works/life/operating-system-experiment/ParallelCalculationDemo.cpp | 75 |
1 files changed, 0 insertions, 75 deletions
diff --git a/works/life/operating-system-experiment/ParallelCalculationDemo.cpp b/works/life/operating-system-experiment/ParallelCalculationDemo.cpp deleted file mode 100644 index 0174c55..0000000 --- a/works/life/operating-system-experiment/ParallelCalculationDemo.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "Thread.h" - -#include <iostream> - -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"; - return -1; - } - } else { - std::cerr << "Too many arguments.\n"; - return -1; - } - - 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<cru::Thread> threads(thread_number); - std::vector<long long> 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 <= N; 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; -} |