If you truly want to print the number of iterations at the end of your program outside of your parallel region or other code you did (and avoid false sharing) the simple solution is to use threadprivate
.
#include <stdio.h>
#include <omp.h>
int iters;
#pragma omp threadprivate(iters)
int main(void) {
omp_set_dynamic(0); //Explicitly turn off dynamic threads
int i;
int n = 10000;
#pragma omp parallel for schedule(dynamic)
for(i=0; i<n; i++) {
iters++;
}
#pragma omp parallel
#pragma omp critical
printf("Thread %d did %d iterations\n", omp_get_thread_num(), iters);
}
Here is a complicated solution which also requires you to change the structure of your code.
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(void) {
int i;
int n = 100;
int nthreads;
int *aiters;
#pragma omp parallel
{
nthreads = omp_get_num_threads();
#pragma omp single
aiters = malloc(sizeof *aiters * nthreads);
int iters = 0;
#pragma omp for schedule(dynamic)
for(i=0; i<n; i++) {
iters++;
}
aiters[omp_get_thread_num()]=iters;
}
for(i=0; i<nthreads; i++)
printf("Thread %d did %d iterations\n", i, aiters[i]);
free(aiters);
}