title: Using thread private variables in dynamic DLLs?
body: <p>I am looking for some advice about OpenMP. I am confused about the use of threadprivate variables. The problem can be presented in the following example:</p>
  
  <pre><code>-----------
  
  // The code below is located the dynamically loaded DLL.
  /* Global variable. */
  int *p;
  #pragma omp threadprivate(p)
  
  extern "C" __declspec(dllexport) int MyFunc1(void)
  {
    int i;
    #pragma omp parallel for
    for (i = 0; i &lt; n; i++) {
       MyFunc2(i);
    }
     return TRUE;
  }
  
  void MyFunc2(void)
  {
      p  = malloc(sizeof(int));
     *p  = 0;
      printf(“value = %d”,*p);
      free(p);
  }
  
  -----------
  </code></pre>
  
  <p>Here I want each thread to have a separate copy of a global thread-independent variable that will be visible in all functions of the thread. The variable will be initialized and destroyed within the thread.</p>
  
  <p>The “problem” here is that all code including definition of the global variable “p” is located the dynamically loaded DLL (via LoadLibrary).  </p>
  
  <p>Microsoft says<a href="http://msdn.microsoft.com/en-us/library/2z1788dd.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/2z1788dd.aspx</a>: <em>“You cannot use threadprivate in any DLL that will be loaded via LoadLibrary. This includes DLLs that are loaded with /DELAYLOAD (Delay Load Import), which also uses LoadLibrary.”</em> So, if I got it right, the above code is not correct – threadprivate variables and dynamically loaded DLL do not mix.</p>
  
  <p>To verify this I created a test project that dynamically loads a DLL add runs a function in parallel using threadprivate as described above. It all worked just fine! </p>
  
  <p>Hmmm ... Now I am confused because that project was not supposed to work.</p>
  
  <p>Can I really use thread private variables in dinamic DLLs or is there a trick to this?</p>
  
  <p>Thank you,</p>
  
  <p>Alex</p>