title: Closing thread using ExitThread - C
body: <p>I have a simple program that creates a thread, loops twenty times and then makes a call to close itself and perform the necessary cleanup.</p>
  
  <p>When I debug the program it reaches the ExitThread(); method and pauses, ignoring the printf(); I have set up after it to signal to me it's closed.</p>
  
  <p>Is this normal or am I forgetting to do something? I'm new to threading using C.</p>
  
  <p><strong>Main()</strong></p>
  
  <pre><code>void main()
  {
      Time t;
      int i = 0;
  
      StartTimer();
  
      for(i = 0; i &lt; 20; i++)
      {
          t = GetTime();
          printf("%d.%.3d\n", t.seconds, t.milliseconds);
          Sleep(100);
      }
      StopTimer();
  }
  </code></pre>
  
  <p><strong>Thread Creation</strong></p>
  
  <pre><code>void StartTimer()
  {
      DWORD threadId;
  seconds = 0;
  milliseconds = 0;
  
  // Create child thread
  hThread = CreateThread(
      NULL,       // lpThreadAttributes (default)
      0,          // dwStackSize (default)
      ThreadFunc, // lpStartAddress
      NULL,       // lpParameter
      0,          // dwCreationFlags
      &amp;threadId   // lpThreadId (returned by function)
      );
  
  // Check child thread was created successfully
  if(hThread == NULL)
  {
      printf("Error creating thread\n");
  }
  }
  </code></pre>
  
  <p><strong>Thread Close</strong></p>
  
  <pre><code>void StopTimer()
  {
      DWORD exitCode;
  
      if(GetExitCodeThread(hThread,&amp;exitCode) != 0)
      {
          ExitThread(exitCode);   
          printf("Thread closed");
  
          if(CloseHandle(hThread))
          {
              printf("Handle closed");
          }
      }
  }
  </code></pre>
  
  <p><strong>Edit:</strong></p>
  
  <p>I've realised that ExitThread() stops the executing thread, therefore I have attempted to use a different method to stop the timer but i'm still left with the same result.</p>
  
  <pre><code>void StopTimer()
  {    
      WaitForSingleObject(hThread,INFINITE);
  }
  </code></pre>
  
  <p><strong>Solution:</strong></p>
  
  <p>The reason the program was stopping at the WaitForSingleObject() call and not progressing no matter how long it took was because the operation it was waiting on had an infinite loop.</p>
  
  <p>It would be waiting for an infinite loop to finish, not the best thing to do. Changing the delay of WaitForSingleObject() to something more reasonable, such as 100 allowed the program to run normally.</p>
  
  <p>Thanks for all the input.</p>