race condition


The following program demonstrates a race condition, whereby two threads try to increment the same counter.

To run program, simply enter:


      ./inc_unsafe NUM_LOOPS
      
inc_unsafe.c


      

For instance, we would expect


      ./incr_unsafe 10000
      

to output 20000, but instead it outputs some smaller value, such as 12988.

The solution is to protect the critical section of code that accesses the shared variable with a mutex:

inc_safe.c


      

The complete source code for the two programs is available as a zip file.