Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22067

OpenMP tasks don't see changes of shared variables

$
0
0

I start two OpenMP tasks that simply print the value of a shared variable initially set to 1. I change the variable between starting the two tasks to 2.

I'd expect both tasks to see the changed value of the variable, that is the output should be 2 2. However I always get 1 2 or 2 1, which is the result I'd expect if the variable was firstprivate.

I also tried to set a lock before starting the tasks and unset it after they are registered and the variable is changed. Also made both tasks wait for the lock to ensure the variable has already changed. The result is the same, I’m not getting both tasks to see the changed value of the variable (2 2). What am I getting wrong? Using GCC 7.4.0. omp_get_num_threads returns 8.

#include <iostream>
#include <omp.h>

int main()
{
    omp_lock_t lock;
    int i = 1;
    omp_init_lock(&lock);
    #pragma omp parallel default(shared) shared(i)
    {
        #pragma omp single
        {
            omp_set_lock(&lock); // set lock before any tasks are registered
            #pragma omp task default(shared) shared(i)
            {
                omp_set_lock(&lock); // should wait until lock is unset and i is 2?
                std::cout << i;
                omp_unset_lock(&lock);
            }
            i = 2;
            #pragma omp task default(shared) shared(i)
            {
                omp_set_lock(&lock);
                std::cout << i;
                omp_unset_lock(&lock);
            }
            omp_unset_lock(&lock); // unset lock after i is set to 2
        }
    }
    omp_destroy_lock(&lock);
    return 0;
}

Edit. Maybe i is not stored in shared memory for some reason? If I change it to something that can't be stored in a register, or make it global, or even just print it's address (std::cout << &i;), the program works as expected. Possibly undefined behaviour or a GCC issue?


Viewing all articles
Browse latest Browse all 22067

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>