title: Calling a function when thread is exiting in PThreads or Windows
body: <p>I am creating a C++ library for both Linux (with PThreads) and Windows (with their built-in WinThreads) which can be attached to any program, and needs to have a function called when the thread is exiting, similar to how atexit works for processes. </p>
  
  <p>I know of pthread_cleanup_push and pthread_cleanup_pop for pthreads, but these do not work for me since they are macros that add another lexical scope, whereas I want to declare this function the first time my library is called into, and then allow the program itself to run its own code however it needs to. I haven't found anything similar in Windows whatsoever. </p>
  
  <p>Note that this doesn't mean I want an outside thread to be alerted when the thread stops, or even that I can change the way the thread will be exited, since that is controlled by the program itself, my library is just attached, along for the ride.</p>
  
  <p>So the question is: <strong>What is the best way, in this instance, for me to have a function I've written called when the thread closes, in either Windows or Linux, when I have no control over how the thread is created or destroyed?</strong></p>
  
  <p>For example in main program:</p>
  
  <pre><code>void* threadFunc(void* arg)
  {
      printf("Hello world!\n");
      return NULL;
  }
  
  int main(int argc, char** argv)
  {
      int        numThreads = 1;
      pid_t*     pids       = NULL;
      pids     = (pid_t*)     calloc(sizeof(pid_t), numThreads);
  
      pthread_create(&amp;ntid, NULL, threadFunc, &amp;nVal);
      pthreads[0] = ntid;
  
      pthread_join(pthreads[0], NULL);
      return 0;
  }
  </code></pre>
  
  <p>In library:</p>
  
  <pre><code>void callMeOnExit()
  {
      printf("Exiting Thread!\n");
  }
  </code></pre>
  
  <p>I would want for callMeOnExit to be called when the thread reaches return NULL; in this case, as well as when the main thread reaches the return 0;. Wrapping pthread_exit would work for other cases, and could be a solution, but I'd like a better one if possible.</p>
  
  <p>If anyone has any ideas on how I might be able to do this, that would be great!</p>