Skip to content

Instantly share code, notes, and snippets.

@stormxuwz
Last active January 12, 2024 10:21
Show Gist options
  • Save stormxuwz/1c9c4bb52016f83ac79f to your computer and use it in GitHub Desktop.
Save stormxuwz/1c9c4bb52016f83ac79f to your computer and use it in GitHub Desktop.
parallel while loop
// 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);
}
}
}
@syang-creater
Copy link

Thank you for explaining more details of the code. I am learning openMP right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment