title: Threads are stuck in an infinite loop while waiting for a variable to change
body: <p>Here's piece of code for my threads learning test:</p>
  
  <pre><code>int mylock = 0;
  
  void *r1(void *x)
  {
    puts("entered r1");
    int *p;
    p = (int *)x;
    int i = *p;
    sleep(1);
    *p = --i;
    printf("r1: %d\n",*p);
    mylock = 1;
    printf("r1: done\n");
  #ifdef USETHREADS
    pthread_exit(0);
  #endif
  }
  
  void *r2(void *x)
  {
    puts("entered r2");
    if (!mylock) {
            puts("r2 is waiting...");
            while (!mylock)
                  printf("");
    }
    int *p;
    p = (int *)x;
    int i = *p;
    *p = ++i;
    sleep(1);
    printf("r2: %d\n",*p);
    printf("r2: done\n");
  #ifdef USETHREADS
    pthread_exit(0);
  #endif
  }
  
  main()
  {
    int i1,i2;
    i1 = 1;
    i2 = 2;
    printf("i1: %d\n", i1);
  #ifdef USETHREADS
    pthread_t r1_thread, r2_thread;
    pthread_create(&amp;r1_thread, NULL, r1, &amp;i1);
    pthread_create(&amp;r2_thread, NULL, r2, &amp;i1);
    pthread_join(r1_thread, NULL);
    pthread_join(r2_thread, NULL);
  #else
    r1(&amp;i1);
    r2(&amp;i1);
  #endif
    printf("i1: %d\n", i1);
    return 0;
  }
  </code></pre>
  
  <p>So two threads, one is increasing i1 and one decreasing (I am aware of "mutexes" in pthreads, not using at this time though), so to avoid race condition I create mylock (which fakes mutex i guess), and what surprises me is the process gets stuck in an indefined loop while waiting for mylock to change value, <em>unless</em> i call <code>printf</code> in a wait loop, with printf call it exits in just as expected 2sec, is that linux mistery?</p>