Search code examples
cmultithreadingparallel-processingopenmp

Track progress in a thread with OpenMP


Im trying to create a programm that displays value from different thread every second, as an attempt at progress tracking functionality, but unfortunatly i cant seam to correctly parallelise this case at all.

Here is my attempt:

#include <stdio.h>
#include <omp.h>

volatile int counter = 0;
volatile int done = 0;

void print_every_second() {
    while (!done) {
        #pragma omp critical
        {
            printf("%d\n!", counter);
        }
        sleep(1);
    }
}

void increment_to_10_million() {
    for (int i = 1; i <= 10000000; ++i) {
        #pragma omp atomic
        counter++;
    }
    done = 1; 
}

int main() {
    #pragma omp parallel sections
    {
        #pragma omp section
        {
            print_every_second();
        }

        #pragma omp section
        {
            increment_to_10_million();
        }
    }

    printf("Both threads have finished.\n");

    return 0;
}

Functions end up not beign parallelised and only print_every_second ends up executing, at all. It is tested in VirtualBox with AMD Ryzen™ 7 2700 × 4 and gcc (Debian 12.2.0-14) 12.2.0


Solution

  • Ok so i found an answer, and to some people who are more knowledgeable on omp this will be obvious.

    The issue was solved by specifying number of threads using as by default it was using only 1 thread, basically making all pragma statements nonexistent.

    Here is a corrected section:

    int main() {
        #pragma omp parallel sections num_threads(2)
        {