Write a program that uses multiple threads to calculate the sum of the squares of all numbers from 1 to N, where N is a positive integer entered by the user. Use multi-threading to speed up the computing process.
Require:
(1) Use the C++ thread library (std::thread) to implement multi-threading.
2) The program should be able to handle larger N values to ensure the accuracy and efficiency of calculation results. "Programs should have good thread synchronization and data sharing mechanisms to avoid race conditions and data inconsistency problems
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex mtx;
long long sum = 0;
void square_sum(int start, int end) {
long long partial_sum = 0;
for (int i = start; i <= end; i++) {
partial_sum += i * i;
}
std::unique_lock<std::mutex> lock(mtx);
sum += partial_sum;
}
int main() {
int N;
std::cout << "Enter a positive integer: ";
std::cin >> N;
int num_threads = std::thread::hardware_concurrency();
std::vector<std::thread> threads(num_threads);
int chunk_size = N / num_threads;
for (int i = 0; i < num_threads; i++) {
int start = i * chunk_size + 1;
int end = (i == num_threads - 1) ? N : (i + 1) * chunk_size;
threads[i] = std::thread(square_sum, start, end);
}
for (auto& t : threads) {
t.join();
}
std::cout << "The sum of squares from 1 to " << N << " is " << sum << std::endl;
return 0;
}