title: Graceful termination of a thread
body: <p>Consider a multithreaded windows server application. for the sake of generality, let us assume all threads are running the same function:</p>
  
  <pre><code>DWORD WINAPI threaded_function(LPVOID p)
  {
    while (TRUE) { // do things } 
  }
  </code></pre>
  
  <p>Also , lets assume we're keeping references for all these threads.
  What would be the best practice for a graceful termination?
  (Keep in mind that as a service , we share a process among an unknown number of services and any kind of process termination methods are out of question) </p>
  
  <p>My best guess would be:</p>
  
  <ol>
  <li><p>Altering the <code>while (TRUE)</code> statement , with <code>while(global_event.not_signaled() )</code> (<code>where global_event</code> is an instance of a class that wrap the <code>Win32</code> <code>Event</code> object and the method called is obvious) </p></li>
  <li><p>Now, implement the termination function as follow:</p>
  
  <p>global_event.set();
   Sleep(/* what would be a reasonable time to wait here? */ );
   thread_container.terminate_all();</p></li>
  </ol>
  
  <p>The restriction we have, is that the application must eventually finish execution of all of it thread, and release all of it's VM and resources among of which are the thread's kernel objects.</p>
  
  <p>Is there any better way to do this? are there any disadvantages in the specified method?</p>