SWE2017 - Lab Assignment 1pages-7
SWE2017 - Lab Assignment 1pages-7
Lab Assignment- 6
1.
Code:
#include <stdio.h>
#include <omp.h>
if (omp_get_thread_num() == 0)
{
printf("Sum using reduction: %d\n", sum);
double formula_start_time = omp_get_wtime();
int formula_sum = p * (p + 1) / 2;
double formula_end_time = omp_get_wtime();
return 0;
}
Output:
SWE2017 - Parallel Programming Lab Assignment – 6
2.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int is_prime(int n)
{
if (n <= 1)
return 0;
if (n <= 3)
return 1;
if (n % 2 == 0 || n % 3 == 0)
return 0;
for (int i = 5; i * i <= n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return 0;
}
return 1;
}
int main()
{
int count = 0;
Output:
3.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <omp.h>
int main()
{
bool *is_prime = (bool *)malloc(LIMIT * sizeof(bool));
int max_gap = 0;
generate_primes(is_prime);
primes[num_primes++] = i;
}
}
free(is_prime);
free(primes);
return 0;
}
Output:
4.
Code:
#include <stdio.h>
#include <omp.h>
int main() {
int total_population = 500;
int growth_rates[4] = {10, 15, 20, 5};
Output:
If we are starting with a total population of 500, and assuming the threads are updating the
population in the order of their ranks:
Thus, the expected final population count after all colonies contribute in this iteration is
550.
The #pragma omp critical directive is essential here because it ensures that only one
thread at a time updates the total_population variable. Without it, multiple threads
might attempt to read, modify, and write to total_population simultaneously, leading to
data races. For example, if two threads read the same initial population value before
updating it, both might add their increments to the old value, resulting in an incorrect final
population count.
Performance Consideration
While #pragma omp critical prevents data races, it can also introduce thread contention
because only one thread can enter the critical section at any time. This serialization can
reduce performance, particularly if the critical section is in a loop or if there are many
threads. In cases where performance is critical and the shared update is frequent,