#include #include // Atencao! #include #include #include #include int main(int argc, char *argv[]) { if (argc != 3) { std::cerr << "Please, give the number of elements and number of threads in " "the command line.\n"; return 1; } int const N = std::stoi(argv[1]); if (N <= 0) { std::cerr << "Number of elements must be positive.\n"; return 2; } int const num_threads = std::stoi(argv[2]); if (num_threads <= 0) { std::cerr << "Number of threads must be positive.\n"; return 2; } // Create an array from 0 to N-1. std::vector array(N); std::iota(begin(array), end(array), 0); // A function to compute the sum of a part of the array. auto part_sum = [&array = std::as_const(array), num_threads](int tid) { std::int64_t sum = 0; for (size_t j = tid; j < array.size(); j += num_threads) { sum += array[j]; } return sum; }; // To execute a thread and get its return value later, we use futures. std::vector> results; for (int i = 0; i < num_threads; ++i) { // Define a lambda function for the thread code. // Execute asynchronously and get a future with the result. results.emplace_back(std::async(std::launch::async, part_sum, i)); } // Now we get the values from the futures and add them to sum. std::int64_t sum = 0; for (auto &res : results) { // Wait for the thread to finish and get the returned value. sum += res.get(); } std::int64_t n64 = N; if (sum == n64 * (n64 - 1) / 2) { std::cout << "Nice, I can sum!" << std::endl; } else { std::cout << "Back to school!" << std::endl; } return 0; }