Using Common Variables

User variables that are referenced by multiple threads should have the attribute volatile to ensure that all changes to the value of the variable are performed immediately by the compiler.

User variables that are referenced by multiple threads and are not declared using the __thread attribute, should have the attribute volatile to ensure that all changes to the value of the variable are seen immediately by other threads.

For example, because of the way the compiler optimizes code, the following example may not work as intended when compiled with the /O+ compiler option:

 static int common_var;

/*  code executing in thread 1  */

   common_var = 0;
       ...
   common_var = 1;
       ...
   common_var = 2;

/*  code executing in thread 2  */

   switch (common_var)
   {
      case 0:
          ...
        break;
      case 1:
          ...
        break;
      default:
          ...
        break;
    }

When optimizing, the compiler may not immediately store the value1 for the variable common_var in thread 1. If it determines that common_var is not accessed by this code until after the value 2 is stored, it may never store the value 1. Thread 2 therefore does not necessarily access the true value of common_var.

Declaring a variable as volatile indicates to the compiler that references to the variable have side effects, or that the variable may change in ways the compiler cannot determine. Optimization will not eliminate any action involving the volatile variable. Changes to the value of the variable are then stored immediately, and uses of the variable will always cause it to be re-fetched from memory (in case its value has been altered by another thread).



Multithreaded Applications
Optimize Your Application


Summary of Compiler Options