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 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 } }