Skip to content

Commit

Permalink
Episode 4 code updates: added barrier example code
Browse files Browse the repository at this point in the history
  • Loading branch information
mehtaparabaci committed Dec 2, 2024
1 parent 21f135d commit f4bfb83
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions high_performance_computing/hpc_openmp/code/examples/04-barriers.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <omp.h>
#include <stdio.h>

#define TABLE_SIZE 8

/* Function to initialise the lookup table */
void initialise_lookup_table(int thread_id, double lookup_table[TABLE_SIZE]) {
int num_threads = omp_get_num_threads();
for (int i = thread_id; i < TABLE_SIZE; i += num_threads) {
lookup_table[i] = thread_id * 2; /* Each thread initialises its own portion */
printf("Thread %d initializing lookup_table[%d] = %f\n", thread_id, i, lookup_table[i]);
}
}

/* Function to perform the main calculation */
void do_main_calculation(int thread_id, double lookup_table[TABLE_SIZE]) {
int num_threads = omp_get_num_threads();
for (int i = thread_id; i < TABLE_SIZE; i += num_threads) {
printf("Thread %d processing lookup_table[%d] = %f\n", thread_id, i, lookup_table[i]);
}
}

int main() {
double lookup_table[TABLE_SIZE] = {0}; /* Initialise the lookup table to zeros */

#pragma omp parallel
{
int thread_id = omp_get_thread_num();

/* The initialisation of the lookup table is done in parallel */
initialise_lookup_table(thread_id, lookup_table);

#pragma omp barrier /* As all threads depend on the table, we have to wait until all threads
are done and have reached the barrier */


/* Each thread then proceeds to its main calculation */
do_main_calculation(thread_id, lookup_table);
}

return 0;
}

0 comments on commit f4bfb83

Please sign in to comment.