Skip to content

Instantly share code, notes, and snippets.

@bfraboni
Created September 4, 2019 13:06
Show Gist options
  • Save bfraboni/fef256d1a058742f403129e10aa5ba6a to your computer and use it in GitHub Desktop.
Save bfraboni/fef256d1a058742f403129e10aa5ba6a to your computer and use it in GitHub Desktop.
Task concurrency using nested parallelism with OpenMP
#include <cstdio>
#include <chrono>
#include <omp.h>
void viewer( int& a, bool& stop )
{
printf("thread %d start viewer\n", omp_get_thread_num());
auto start = std::chrono::high_resolution_clock::now();
while( !stop )
{
auto now = std::chrono::high_resolution_clock::now();
long int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
// print every 100 milliseconds
if ( elapsed % 100 == 0 )
{
// printf("thread %d a = %d at %ld ms\n",omp_get_thread_num(), a, elapsed);
}
}
printf("thread %d stop viewer\n", omp_get_thread_num());
}
void render( int& a, bool& stop )
{
printf("thread %d start render\n", omp_get_thread_num());
int loop = 0;
while( true )
{
printf("loop %d\n", loop);
int mod = 300000;
// all remaining threads should be used here
#pragma omp parallel for schedule(dynamic, 16)
for(int i = 0; i < 1000 * 1000; ++i)
{
#pragma omp atomic
a++;
if( i % mod == 0 )
{
printf("thread %d working %d available %d\n", omp_get_thread_num(), omp_get_num_threads(), omp_get_max_threads() - omp_get_num_threads());
}
}
if( a > 100000000 ) break;
loop++;
}
// stop live viewer at the end of render
stop = true;
printf("thread %d stop render\n", omp_get_thread_num());
}
int main( )
{
// max threads
int nb = omp_get_max_threads();
printf("threads %d\n", nb);
// enable nested parallelism
omp_set_nested(1);
// var
int a = 0;
bool stop = false;
// 2 parallel tasks : 1 use nested parallelism
#pragma omp parallel sections num_threads(2)
{
// live viewer
#pragma omp section
{
viewer(a, stop);
}
// render
#pragma omp section
{
render(a, stop);
}
}
printf("a %d\n", a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment