From 0fc5d70225f616c614b194f91e5a6a31c2416fb7 Mon Sep 17 00:00:00 2001 From: gajendra Date: Mon, 21 Oct 2024 00:04:45 +0530 Subject: [PATCH 1/2] chore: Ensure all tasks are completed before returning the final sum --- Hello-Foss-PyThread.cpp | 1 + 1 file changed, 1 insertion(+) create mode 160000 Hello-Foss-PyThread.cpp diff --git a/Hello-Foss-PyThread.cpp b/Hello-Foss-PyThread.cpp new file mode 160000 index 0000000..12f174f --- /dev/null +++ b/Hello-Foss-PyThread.cpp @@ -0,0 +1 @@ +Subproject commit 12f174fb8de387bfd7fa2b1609c5918bddd5ef07 From 1fb23809893f3a98f3cd4eca21ec4992aa3f87e5 Mon Sep 17 00:00:00 2001 From: gajendra Date: Mon, 21 Oct 2024 11:11:02 +0530 Subject: [PATCH 2/2] Ensure all tasks are completed before returning the final sum --- src/wrong_sum.cpp | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/src/wrong_sum.cpp b/src/wrong_sum.cpp index fd04ade..f89c8aa 100644 --- a/src/wrong_sum.cpp +++ b/src/wrong_sum.cpp @@ -1,4 +1,4 @@ -#include "parallel_sum.h" +#include "paralle_sum.h" #include #include @@ -7,31 +7,33 @@ int parallel_sum(const int arr[], int size, int step_size) { #pragma omp parallel { - - for (int i = 0; i < size; i += step_size) { - int start = i, end = i + step_size - 1; - - // Ensure end index is within bounds - if (end >= size) end = size - 1; - - std::cout << "Thread computing Sum(" << start << "," << end << ") from " - << omp_get_thread_num() << " of " << omp_get_num_threads() << std::endl; - - #pragma omp task - { - int psum = 0; - std::cout << "Task computing Sum(" << start << "," << end << ") from " - << omp_get_thread_num() << " of " << omp_get_num_threads() << std::endl; - - for (int j = start; j <= end; j++) { - psum += arr[j]; - } + #pragma omp single // Ensure only one thread creates tasks + { + for (int i = 0; i < size; i += step_size) { + int start = i, end = i + step_size - 1; + + // Ensure end index is within bounds + if (end >= size) end = size - 1; - #pragma omp critical + #pragma omp task // Create a task for summation { - sum += psum; + int psum = 0; + std::cout << "Task computing Sum(" << start << "," << end << ") from " + << omp_get_thread_num() << " of " << omp_get_num_threads() << std::endl; + + for (int j = start; j <= end; j++) { + psum += arr[j]; + } + + #pragma omp critical // Critical section to update global sum + { + sum += psum; + } } } + + // Ensure all tasks are completed before returning the final sum + #pragma omp taskwait } }