title: Synchronize three processes to print letters in a certain order
body: <p>I have three processes that can print one letter, A, B and C. </p>
  
  <p>I want the following output.</p>
  
  <pre><code>AB AC AB AC AB .....
  </code></pre>
  
  <p>I have three binary semaphores initialized to the following values:</p>
  
  <pre><code>print_a = 1
  print_b = 0
  print_c = 0
  </code></pre>
  
  <p>Process A:</p>
  
  <pre><code>while(1) {
      wait(print_a);
  
      sleep(2); //So it's possible to see the output properly
      printf(" A");
      fflush(stdout);
  
      signal(print_b); 
  }
  </code></pre>
  
  <p>Process B:</p>
  
  <pre><code>while(1) {
      wait(print_b);
  
      printf("B");
      fflush(stdout);
  
      signal(print_a);
      wait(print_b);
  
      signal(print_c);
  }
  </code></pre>
  
  <p>Process C:</p>
  
  <pre><code>while(1) {
      wait(print_c);
  
      printf("C");
      fflush(stdout);
  
      signal(print_a);
  }
  </code></pre>
  
  <p>Signal and wait are implemented using the filesystem. Wait is a spinlock trying to remove a file until it's successful. Signal creates a file.</p>
  
  <pre><code>void wait(char * file){
      while(unlink(file) != 0);
  
  }
  
  void signal(char * file){
      if(open(file, O_CREAT | O_RDWR, 00777) == -1) {
          printf("Failed to open %s\n", file);
          exit(-1);
      }
  }
  </code></pre>
  
  <p>For the most part I get the correct output I want. However, occasionally the output will be wrong. </p>
  
  <p>This is an example of the output:</p>
  
  <pre><code>AB AC AB AC AB AC AB AC AB AC AB AC AB AB AC AC AB AC AB AB AC A &gt;&gt;ACB&lt;&lt; AB AC AC AB AB AC AB
  
  AC ABC AC AB &gt;&gt;ABC&lt;&lt; AB AC AC A AB AC AB AB AC AC AB AB AC &gt;&gt;ABC&lt;&lt; AB AC AC AB AB AC AC AB AB AC
  </code></pre>
  
  <p>I can't seem to figure out what's causing B or C to be printed after B or C instead of A.</p>
  
  <p>UPDATE:</p>
  
  <p>If I change wait to this:</p>
  
  <pre><code>void wait(char * file){
      while(unlink(file) != 0) {
              usleep(1000 * 100);
      }
  }
  </code></pre>
  
  <p>It seems to work fine. Still don't understand why though.</p>