title: Why printf is not working with multple threads in c?
body: <p>In the code below I create 8 threads and each of those prints a string and its id. However, I don't see any <code>printf</code> output in <code>stdout</code> from <code>PrintHello</code> function. One strange thing that is happening is that if run the <code>main</code> using debugger (CLion) <code>printf</code> indeed outputs the intended output. I actually suspect that no code inside  <code>PrintHello</code> function is run, not just <code>printf</code>. What could be causing this?</p>
  
  <p>Also according to this <a href="https://stackoverflow.com/questions/23586682/how-to-use-printf-in-multiple-threads">answer</a> <code>printf</code> is thread-safe so it shouldn't be an issue of different threads competing for <code>stdout</code>.</p>
  
  <p>This is the code (it as adapted from these <a href="https://courses.engr.illinois.edu/cs241/fa2010/ppt/10-pthread-examples.pdf" rel="nofollow noreferrer">slides</a>):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;ntsid.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  
  #define BAD_EXIT 1
  #define NUM_TASKS 8
  
  char * messages[NUM_TASKS];
  
  void * PrintHello(void * taskIdPtr) {
      int taskId;
      sleep(1);
      taskId = *((int *) taskIdPtr);
      printf("Task id = %d, message = %s\n", taskId, messages[taskId]);
      free(taskIdPtr);
      pthread_exit(NULL);
  }
  int main(int argc, char ** argv) {
      pthread_t threads[NUM_TASKS];
      int * taskIdPtr;
      int rc, t;
      messages[0] = "English: Hello World!";
      messages[1] = "French: Bonjour, le monde!";
      messages[2] = "Spanish: Hola al mundo";
      messages[3] = "Klingon: Nuq neH!";
      messages[4] = "German: Guten Tag, Welt!";
      messages[5] = "Russian: Zdravstvytye, mir!";
      messages[6] = "Japan: Sekai e konnichiwa!";
      messages[7] = "Latin: Orbis, te saluto!";
  
      for(t = 0; t &lt; NUM_TASKS; t++) {
          taskIdPtr = (int *) malloc(sizeof(int));
          *taskIdPtr = t;
          printf("Creating thread %d\n", t);
          rc = pthread_create(&amp;threads[t], NULL, PrintHello, (void *) taskIdPtr);
          if(rc) {
              perror("Error :");
              exit(BAD_EXIT);
          }
      }
      return 0;
  }
  </code></pre>