title: Creating a C++ Non-Blocking Timer in Windows
body: <p>On Linux, I would create a child process using fork() that will be my count-down timer, and once the timer ends, the child process will send a signal to the parent process to tell it that the timer has ended. The parent process then should handle the signal accordingly.</p>
  
  <p>I have no idea how to do this on windows. Some people here recommended using threads but they never wrote any example code showing how to do that.</p>
  
  <p>The most important thing is that the timer is non-blocking, meaning that it remains counting down in the background, while the program is accepting input from the user and handling it normally.</p>
  
  <p>Could you please show me how?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The application is a console one. And please show me example code. Thanks!</p>
  
  <p><strong>Update:</strong></p>
  
  <p>So after I read some of the suggestions here, I searched for some answers here and found this <a href="https://stackoverflow.com/questions/10715555/settimer-in-vc">one</a> which was helpful.</p>
  
  <p>I then wrote the below code, which works, but not as it's supposed to be:</p>
  
  <pre><code>#include &lt;Windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  using namespace std;
  
  #define TIMER_VALUE (5 * 1000) //5 seconds = 5000 milli seconds
  HANDLE g_hExitEvent = NULL;
  
  bool doneInTime = false;
  string name;
  
  bool inputWords();
  
  
  //The below function will be called when the timer ends
  void CALLBACK doWhenTimerEnds(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
  {
      if(!doneInTime)
      {
          cout &lt;&lt; "\nOut of time ... try again ..." &lt;&lt; endl;
          name = "";
          doneInTime = inputWords();
      }
      SetEvent(g_hExitEvent);
  }
  
  
  bool inputWords()
  {
  
      /* doWhenTimerEnds() will be called after time set by 5-th parameter and repeat every 6-th parameter. After time elapses,
      callback is called, executes some processing and sets event to allow exit */
      HANDLE hNewTimer = NULL; 
      BOOL IsCreated = CreateTimerQueueTimer(&amp;hNewTimer, NULL, doWhenTimerEnds, NULL, TIMER_VALUE, 0, WT_EXECUTELONGFUNCTION);
  
      g_hExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  
      cout &lt;&lt; "Input your name in 5 seconds .. " &lt;&lt; endl;
      std::getline(cin, name);
  
      DeleteTimerQueueTimer(NULL, hNewTimer, NULL);
      return true;
  }
  
  int main()
  {
      doneInTime = inputWords();
      cout &lt;&lt; "Hello, " &lt;&lt; name &lt;&lt; "! You're done in time" &lt;&lt; endl;
  
      //WaitForSingleObject(g_hExitEvent, 15000);
  
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>The problem is, the interrupted getline() never stops, and the subsequent getline()'s read even the text previously entered! how can I fix that please? And if there's a better way of doing it, could you please point me out to it?</p>