title: Dynamically creating threads and passing an integer
body: <p>I have a process that creates a number of threads based on an argument passed to the process.</p>
  
  <pre><code>producer_threads[num_threads];
  for (id = 0; id &lt; num_threads; id++)
  {
      printf("%d\n", id);
      pthread_create(&amp;producer_threads[id], NULL, &amp;produce, (void *) &amp;id);
  }
  </code></pre>
  
  <p>Each thread goes into a produce function and stores the id as a local variable</p>
  
  <pre><code>void* produce (void* args)
  {
      int my_id = * (int*) args;
      printf("Thread %d started to produce\n", my_id);
  }
  </code></pre>
  
  <p>However the output I receive is as shown</p>
  
  <pre><code>0
  1
  Thread &lt;n&gt; started to produce
  Thread &lt;n&gt; started to produce
  </code></pre>
  
  <p>and n are randomly either 0, 1, or 2. I am not sure what is causing the problem unless it is because the global variable is being updated before it is assigned locally. Or because the "local variable" is shared between threads.</p>