I am testing out how threadprivate clause works in openMP. I set up the following simple test case
#include <iostream>
#include <omp.h>
void func(){
static int some_id = omp_get_thread_num();
#pragma omp threadprivate(some_id)
#pragma omp critical
{
std::cout << "id:" << some_id << std::endl;
std::cout << "in thread " << omp_get_thread_num() << std::endl;
}
}
int main() {
omp_set_num_threads(4);
#pragma omp parallel
func();
}
I compiled this code with gcc7.2 and ran it and I got
id:1
in thread 1
id:0
in thread 0
id:0
in thread 3
id:0
in thread 2
I know that C++ standard (at least since C++03 standard) guarantees that static variables are initialized by one and only one thread and all other threads are blocked until the initialization is complete. With that said, I expected that the local copy of id in all threads possesses the same value (the id of the thread that took care of initialization). Why is id in thread#1 is different from the one in other threads? Clearly my mental model of threadprivate is flawed. Can you explain what is going on here?