title: Why this test application gives different results on different machines? (about post-increment and thread-safe)
body: <p>I heard people say that statements such as var++ and ++var are not threads safe, so I wrote an application to have the test. Code is as below:</p>
  
  <pre><code>   unsigned long gCounter = 0;
     const unsigned long WORKS = 1048576;  // pow(2, 20)
     const unsigned long MAX_THREADS = 100;
     const unsigned long WORKER_THREADS = 2;
  
     unsigned long GetCounter(){
             return gCounter++;
     }
  
     void *WorkerThread(void *){
             unsigned long items = 0;
             do {
                  GetCounter();
                  items++;
             } while(items &lt; WORKS);
  
             printf("Exiting thread: %lu\n", pthread_self());
             return NULL;
      }
  
  
      int main(int argc, char* argv[]){
           pthread_t workers[MAX_THREADS];
  
           //create two threads
           for (int i = 0; i &lt; WORKER_THREADS; i++){
              pthread_create(&amp;workers[i], NULL, WorkerThread, NULL);
           }
  
           //wait for above threads to exit
           for (int i = 0; i &lt; WORKER_THREADS; i++){
                 pthread_join(workers[i], NULL);
           }
  
  
           assert( gCounter == (WORKER_THREADS * WORKS));
           return 0;
      }
  </code></pre>
  
  <p>If the post-increment operation is not thread safe, then above test application will fail sometimes (might be successful). But to my surprise, it always succeeds during 200 tests when running on our server, while on my PC it never succeeds. </p>
  
  <p>Why would this happen? Why would above appcation succeed all the time on our server? Below is information about the Server and my PC:     </p>
  
  <pre><code>     Server machine:
       System: Redhat 3.4.2 - 6.FC3  Kernel: LINUX.2.6.10 
       GCC Version: 3.4.2 20041017   
       CPU: AMD Opteron Processor 144 X86_64
  
       My PC:
       System: ubuntu 3.2.0-40-generic  Kernel: LINUX.3.4
       GCC Version: 4.6.3 (Ubuntu/Linaro )    
       CPU: Intel(R) Pentium(R) Dual  CPU  T2370        
  
       Build Command (both are the same, turn off optimization)
       g++ -O0 -o test test.cpp -lpthread
  </code></pre>
  
  <p><strong>UPDATE</strong><br>
  Today I found that <strong>the server whose CPU is AMD Opteron 144 is a single-cpu-single-core machine</strong>, maybe it is the reason why this test application never fails on it. As my understanding, a single-cpu-single-core machine doesn't support real thread Parallelism, the threads run in order in a very fast pace that they seem to run parallelly, but they really are not and some thread synchronization problems are not likely to occur easily on this kind of machines.</p>