title: Multithreading and O3 compilation in C
body: <p>I'm writing code that tries to detect when i signal changes from 0 to 1 as fast as possible (real time application). I have the following two functions</p>
  
  <pre><code>void *SensorSignalReader (void *arg)
  {
  
    char buffer[30];
    struct timeval tv;
    time_t curtime;
  
    srand(time(NULL));
  
    while (1) {
      int t = rand() % 10 + 1; // wait up to 1 sec in 10ths
      usleep(t*100000);
  
      int r = rand() % N;
      signalArray[r] ^= 1;
  
      if (signalArray[r]) {
        changedSignal = r;
        gettimeofday(&amp;tv, NULL);
        timeStamp[r] = tv;
        curtime = tv.tv_sec;
        strftime(buffer,30,"%d-%m-%Y  %T.",localtime(&amp;curtime));
        printf("Changed %5d at Time %s%ld\n",r,buffer,tv.tv_usec);
      }
    }
  }
  
  void *ChangeDetector (void *arg)
  {
    char buffer[30];
    struct timeval tv;
    time_t curtime;
    int index;
  
    while (1) {
  
      while (changedSignal == -1) {} // issues with O3
      gettimeofday(&amp;tv, NULL);
      index = changedSignal;
      changedSignal = -1;
  
      curtime = tv.tv_sec;
      if(timeStamp[index].tv_usec&gt;tv.tv_usec){
        tv.tv_usec += 1000000;
        tv.tv_sec--;
      }
      strftime(buffer,30,"%d-%m-%Y  %T.",localtime(&amp;curtime));
      printf("Detcted %5d at Time %s%ld after %ld.%06ld sec\n---\n",index,buffer,tv.tv_usec,
      tv.tv_sec - timeStamp[index].tv_sec,
      tv.tv_usec - timeStamp[index].tv_usec);
    }
  }
  </code></pre>
  
  <p>I have 2 pthreads running at all times, one for each function.
  When i compile normally (<code>gcc -lpthread</code>) This works as intended. <code>SensorSignalReader</code> changes <code>changedSignal</code> and <code>ChangeDetector</code> detects it as the while loop breaks. When I compile with the <code>-O3</code> or flag though it feels like the variable <code>changedSignal</code> never changes? The while loop in <code>ChangeDetector</code> runs forever while signals are being changed constantly. If I put a <code>printf("%d\n",changedSignal);</code> inside there, it prints -1 all the time. There is something done by O3 that I do not understand. What is it?</p>