title: In a C program for adding up to a number then subtracting back to 0 using two parallel threads, I get a non-zero answer. This seems impossible
body: <p>The program in question is this one:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;pthread.h&gt;
  #include &lt;stdio.h&gt;
  
  #define NUM_LOOPS 500000000
  long long sum = 0;
  
  /* Add or subtract the offset specified in arg from the sum NUM_LOOPS times */
  void* counting_function(void* arg) {
      int offset = *(int*)arg;
      for (int i = 0; i &lt; NUM_LOOPS; i++) {
          sum += offset;
      }
      pthread_exit(NULL);
  }
  
  int main(void) {
      // Spawn the threads
      pthread_t id1;
      int offset1 = 1;
      pthread_create(&amp;id1, NULL, counting_function, &amp;offset1);
  
      pthread_t id2;
      int offset2 = -1;
      pthread_create(&amp;id2, NULL, counting_function, &amp;offset2);
  
      // Wait for threads to finish
      pthread_join(id1, NULL);
      pthread_join(id2, NULL);
  
      printf("Sum = %lld\n", sum);
  
      return 0;
  }
  </code></pre>
  
  <p>I have a global variable <code>long long sum = 0</code>
  and a macro for <code>NUM_LOOPS 500000000</code> that specifies the number to add up to.</p>
  
  <p>The function <code>void* counting_function(void* arg)</code> just adds the offset to sum <code>NUM_LOOPS</code> times.</p>
  
  <p>If I were to run this without threads but calling the functions one after another like this</p>
  
  <pre><code>// sum is 0
  counting_function(1);
  // sum is now equal to 500000000
  countnig_function(-1); 
  // sum is now equal to 0
  </code></pre>
  
  <p>I would get the correct answer, 0.</p>
  
  <p>But when using threads, I get a non-zero answer, different every time.</p>
  
  <pre><code>gcc -Wall -Wextra -Werror -std=c99 -pthread count.c &amp;&amp; ./a.out
  
  Sum = 40098157
  </code></pre>
  
  <pre><code>./a.out
  Sum = 303575386
  </code></pre>
  
  <p>It seems to me that in whatever order you add or subtract 1 from a number, if the total amount of summations and subtractions is the same, then the answer should always be 0. </p>
  
  <p>For example, let's say that NUM_LOOPS = 10. The first thread adds 1 three times in a row, then the second thread subtracts 1 two times in a row. 
  The sum is now going to be equal to 1. Then the first thread does the remaining seven additions, so sum is equal to 8 and then the second thread subtracts the final eight times. The sum is 0. </p>
  
  <p>How can you possibly get an answer that is different than 0? Having an answer different than 0 would mean that one of the two threads added or subtracted more than the specified amount in NUM_LOOPS.</p>
  
  <p>The problem can be solved by adding mutual exclusion to the critical section <code>sum += offset;</code>
  inside the counting function, but I can't seem to figure out why it wouldn't work without mutex.</p>
  
  <p>What am I missing?</p>