title: How to take input whenever I want during endless loop?
body: <p>My task is to make a game simulation that uses threads to simulate work. If the thread's been given command to do another work it should pause it's first work and start the new work. How to implement it in C? I've tried with separate function for the input and signaling a condition variable but when it enters the giveCommand() function it just waits for input.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  char command;
  pthread_mutex_t mutex;
  pthread_cond_t condVar;
  void giveCommand()
  {
      scanf(&quot;%c&quot;, command);
      pthread_cond_signal (&amp;condVar);
      return;
  }
  void *thread(void *N)
  {
      char c;
      do
      {
          pthread_mutex_lock(&amp;mutex);
          //do its work
          pthread_cond_timedwait(&amp;condVar, &amp;mutex, 500000);// if command hasn't been given, continue work
          pthread_mutex_unlock(&amp;mutex);
          pthread_cond_init(&amp;condVar, NULL);
          while(giveCommand());
      }
  }
      int main()
      {
          int i;
          int error;
          pthread_t threads[NUM_THREADS];
          pthread_mutex_init(&amp;mutex, NULL);
          pthread_cond_init(&amp;condVar, NULL);
          while(1)
          {
              for (i = 0; i &lt; NUM_THREADS; i++)
              {
                  error = pthread_create(&amp;threads[i], NULL, simulateWorker, NULL);
                  if (error != 0) printf(&quot;Error creating thread!&quot;);
              }
              for (i = 0; i &lt; NUM_THREADS; i++)
              {
                  error = pthread_join(threads[i], NULL);
                  if (error != 0) printf(&quot;Error joining thread!&quot;);
              }
              pthread_mutexattr_destroy(&amp;mutex);
          }
          return 0;
      }
  </code></pre>