9.8. Data environment: The threadprivate directive

The threadprivate directive is provided to make file-scope, namespace-scope, or static block-scope variables local to a thread. The syntax of the threadprivate directive is as follows:

#pragma omp threadprivate(variable-list) new-line

Each copy of a threadprivate variable is initialized once, at an unspecified point in the program prior to the first reference to that copy, and in the usual manner (that is, as the master copy would be initialized in a serial execution of the program).

As with any private variable, a thread must not reference another thread’s copy of a threadprivate object. During serial regions and master regions of the program, references will be to the master thread’s copy of the object.

After the first parallel region executes, the data in the threadprivate objects is guaranteed to persist only if the dynamic threads mechanism has been disabled and if the number of threads remains unchanged for all parallel regions.

The following code sample illustrates the use of the threadprivate variable:

/* File: omp_th_private.c */

#include <stdlib.h>
int a, b;
#pragma omp threadprivate(a)

int main(int argc, char *argv[])
{
    /* First parallel region. */
    #pragma omp parallel private(b)
    a = b = 5;

    /* Second parallel region. */
    #pragma omp parallel
    {
        printf("The value of a is %d
", a);
        printf("The value of b is %d
", b);
    }
}

When executed, the program prints the following output:

The value of a is 5
The value of b is 0
The value of a is 5
The value of b is 0
The value of a is 5
The value of b is 0

threadprivate variables differ from private variables because they are able to persist between different parallel sections of a code. That is the reason, in the above output, the value of a is 5 and the value of b is zero or undefined.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset