-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Episode 4 code updates: added barrier example code
- Loading branch information
1 parent
21f135d
commit f4bfb83
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
high_performance_computing/hpc_openmp/code/examples/04-barriers.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |