Shared and private variables in a parallel environment

Variables can have either shared or private context in a parallel environment. Variables in shared context are visible to all threads running in associated parallel loops. Variables in private context are hidden from other threads. Each thread has its own private copy of the variable, and modifications made by a thread to its copy are not visible to other threads.

The default context of a variable is determined by the following rules:

The following code segments show examples of these default rules:
int E1;                        /* shared static     */

void main (argvc,...) {        /* argvc is shared   */
   int i;                       /* shared automatic  */

void *p = malloc(...);       /* memory allocated by malloc   */
                                /* is accessible by all threads */
                                /* and cannot be privatized     */

#pragma omp parallel firstprivate (p)
   {
     int b;                     /* private automatic  */
     static int s;              /* shared static      */

     #pragma omp for
     for (i =0;...) {
       b = 1;                   /* b is still private here !    */
       foo (i);                 /* i is private here because it */
                                /* is an iteration variable     */
      }


#pragma omp parallel
     {
       b = 1;                   /* b is shared here because it  */
                                /* is another parallel region   */
     }
   }
 }


int E2;                        /*shared static */ 

void foo (int x) {             /* x is private for the parallel */
                                /* region it was called from     */
   
int c;                       /* the same */
 ... }
Some OpenMP clauses let you specify visibility context for selected data variables. A brief summary of data scope attribute clauses are listed below:
Data scope attribute clause Description
private The private clause declares the variables in the list to be private to each thread in a team.
firstprivate The firstprivate clause provides a superset of the functionality provided by the private clause.
lastprivate The lastprivate clause provides a superset of the functionality provided by the private clause.
shared The shared clause shares variables that appear in the list among all the threads in a team. All threads within a team access the same storage area for shared variables.
reduction The reduction clause performs a reduction on the scalar variables that appear in the list, with a specified operator.
default The default clause allows the user to affect the data scope attributes of variables.

For more information, see the OpenMP directive descriptions in Pragma directives for parallel processing in the XL C/C++ Compiler Reference. You can also refer to the OpenMP Application Program Interface Language Specification, which is available at http://www.openmp.org.