title: Thread Synchronization at C
body: <p>I have to use two threads; one to do various operations on matrices, and the other to monitor virtual memory at various points in the matrix operation process. This method is required to use a global state variable 'flag'. </p>
  
  <p>So far I have the following (leaving some out for brevity):</p>
  
  <pre><code>int flag = 0;
  
  int allocate_matrices(int dimension)
  {
      while (flag == 0) {} //busy wait while main prints memory state
  
      int *matrix = (int *) malloc(sizeof(int)*dimension*dimension);
      int *matrix2 = (int *) malloc(sizeof(int)*dimension*dimension);
  
      flag = 0;
      while (flag == 0) {} //busy wait while main prints memory state
  
      // more similar actions...
  }
  
  int memory_stats()
  {
      while (flag == 0)
      { system("top"); flag = 1; }
  }
  
  int main()
  { //threads are created and joined for these two functions }
  </code></pre>
  
  <p>As you might expect, the <code>system("top")</code> call happens once, the the matrices are allocated, then the program falls into an infinite loop. It seems apparent to me that this is because the thread assigned to the <code>memory_stats</code> function has already completed its duty, so flag will never be updated again.</p>
  
  <p>Is there an elegant way around this? I know I have to print memory stats four times, so it occurs to me that I could write four while loops in the <code>memory_stats</code> function with busy waiting contingent on the global flag in between each of them, but that seems clunky to me. Any help or pointers would be appreciated.</p>