Last active
January 12, 2024 10:21
-
-
Save stormxuwz/1c9c4bb52016f83ac79f to your computer and use it in GitHub Desktop.
parallel while loop
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
// This code is from https://www.cac.cornell.edu/VW/OpenMP/whileloop.aspx | |
#include <omp.h> | |
#include <stdio.h> | |
int main(int argc, char **argv) | |
{ | |
/* OpenMP does not provide a parallel while loop, | |
so we're going to have to make one ourselves... */ | |
int sj, sstop, tn, tj, tstop; | |
int foo(int j); | |
omp_set_num_threads(8); | |
/* Start carefully - we don't want all threads | |
to (re!)initialize the two shared variables */ | |
sj = -1; // shared loop counter | |
sstop = 0; // shared stopping condition | |
#pragma omp parallel private(tn,tj,tstop) | |
{ | |
tn = omp_get_thread_num(); | |
while (!sstop) | |
{ | |
/* Threads update the shared counter by turns */ | |
#pragma omp critical | |
{ | |
sj++; // increment the shared loop counter... | |
tj = sj; // ...and keep a private copy of it | |
} | |
/* Threads evaulate function foo in parallel */ | |
tstop = foo(tj); | |
/* Flip sstop for everyone if tstop is true in a thread */ | |
if (tstop) | |
{ | |
sstop = 1; | |
#pragma omp flush(sstop) | |
} | |
/* When sstop=1, most threads continue to this statment */ | |
printf("Thread %d, iteration %d, sstop=%d\n",tn,tj,sstop); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for explaining more details of the code. I am learning openMP right now.