Synchronization between Semaphore/Mutex and Printf
<p>I'm working on an exercise (see <strong>bold text</strong> below) on semaphores and synchronization for my Operative System course. The text of the exercise is this:</p>

<p><strong><em>Pthread semaphores and mutexes</em></strong></p>

<blockquote>
  <p>The C program gen_binary_numbers.c receives on the command line an integer n, and uses recursion to generate and display all binary numbers of n bits.<strong>Transform the recursive program into a concurrent one, replacing the recursive procedure with the generation of an appropriate number of processes that display the binary numbers (in any order).</strong></p>
</blockquote>

<p>This is my code, actually:</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;semaphore.h&gt;
#include &lt;pthread.h&gt;

int num, r, c;
pthread_mutex_t mutex;
void *genBin(void *arg);

int main (int argc, char **argv) {
  if (argc != 2) {
    fprintf(stdout, "\nUSAGE: %s &lt;n&gt;\n\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  int i;
  num = atoi(argv[1]);
  c = num;
  r = 2;
  for (i=1; i&lt;num; i++) {
    r=r*2;
  }

  pthread_mutex_init(&amp;mutex, NULL);
  pthread_t* p;
  p = malloc(r*sizeof(pthread_t));

  for (i=0;i&lt;r;i++) {
    if (pthread_create(&amp;p[i], NULL, genBin, &amp;i)) {
      fprintf(stderr, "Error creating thread.\n");
      exit(EXIT_FAILURE);
    }
  }
  pthread_exit(0);
}

void *genBin (void *arg) {
  int x;
  int i=0;
  x = *((int*)arg);

  pthread_mutex_lock(&amp;mutex);

  while (i&lt;num) {
    if(x!=0) {
      fprintf(stdout, "%d", x%2);
    }
    else {
      fprintf(stdout, "0");
    }
    i++;
    x/=2;
  }
  fprintf(stdout, "\n");
  pthread_mutex_unlock(&amp;mutex);
  pthread_exit(0);
}
</code></pre>

<p>I think that the code should return the right solution, but sometimes the output doesn't return the correct number.</p>

<p><strong>Example of correct output:</strong></p>

<pre><code>./genBin 3
100
101
010
110
001
011
111
000
</code></pre>

<p><strong>Example of wrong output (because of duplicates):</strong></p>

<pre><code>./genBin 3
110
110
110
001
011
111
111
000
</code></pre>

<p>I think that the problem is in the synchronization between the mutex and the printf.
Is there an alternative solution to avoid confusing results?</p>