title: pthreads - reading and writing to global variables
body: <p>I am learning about <code>pthreads</code> and I've created a program that creates 10 threads of which 5 read the value of a global variable and 5 update the value of a global variable. Here is some sample output from the program.</p>
  
  <p>My question is why in the <code>write()</code> thread does it always say that the shared variable is 2 even though it is being updated each time a <code>write()</code> thread is created? I would of expected it to change.   </p>
  
  <p>Output: </p>
  
  <pre><code>Write thread - shared variable was 2 and it is now 22
  Read Thread - The shared variable is 2
  Write thread - shared variable was 2 and it is now 9
  Write thread - shared variable was 2 and it is now 12
  Write thread - shared variable was 2 and it is now 37
  Write thread - shared variable was 2 and it is now 43
  Read Thread - The shared variable is 2
  Read Thread - The shared variable is 43
  Read Thread - The shared variable is 43
  Read Thread - The shared variable is 43
  </code></pre>
  
  <p>The code:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  
  
  #define NUM_THREADS 5
  int shared_varibale = 2;
  
  void *read(void *param);
  void *write(void *param);
  
  int main (int argc, char *argv[]) {
  
  
      int i;
      time_t t;
      pthread_t tid[NUM_THREADS];
  
      /* Intializes random number generator */
      srand((unsigned) time(&amp;t));
  
      /*Create 5 write threads*/
          for(i = 0; i &lt; NUM_THREADS; i++) {
              pthread_create(&amp;tid[i], NULL, write, &amp;shared_varibale);
          }
  
      /*Create 5 read threads*/
      for(i = 0; i &lt; NUM_THREADS; i++) {
          pthread_create(&amp;tid[i], NULL, read, &amp;shared_varibale);
      }
  
      return 0;
  }
  
  void *read(void *param) {
      int *p = (int*)param;
      printf("The variable is %d\n", *p);
      pthread_exit(NULL);
  }
  
  
  void *write(void *param) {
  
      int *p = (int*)param;
      int rand_varibale = rand() % 50;
      printf("Write thread - shared variable was %d and it is now %d\n", *p, rand_varibale);
      *p = rand_varibale;
      pthread_exit(NULL);
  }
  </code></pre>