%\pagebreak
\section{\kcode{threadprivate} Directive}
\label{sec:threadprivate}
\index{directives!threadprivate@\kcode{threadprivate}}
\index{threadprivate directive@\kcode{threadprivate} directive}

The following examples demonstrate how to use the \kcode{threadprivate} directive 
 to give each thread a separate counter.

\cexample{threadprivate}{1}

\fexample{threadprivate}{1}

\pagebreak
\begin{ccppspecific}
The following example uses \kcode{threadprivate} on a static variable:

\cnexample{threadprivate}{2}

The following example demonstrates unspecified behavior for the initialization 
of a \kcode{threadprivate} variable. A \kcode{threadprivate}  variable is initialized 
once at an unspecified point before its first reference. Because \ucode{a} is 
constructed using the value of \ucode{x}  (which is modified by the statement 
\ucode{x++}), the value of \ucode{a.val}  at the start of the \kcode{parallel} 
region could be either 1 or 2. This problem is avoided for \ucode{b}, which uses 
an auxiliary \bcode{const} variable and a copy-constructor.

\cppnexample{threadprivate}{3}
\end{ccppspecific}

The following examples show non-conforming uses and correct uses of the \kcode{threadprivate} 
directive. 

\begin{fortranspecific}
The following example is non-conforming because the common block is not declared 
local to the subroutine that refers to it:

\fnexample{threadprivate}{2}

The following example is also non-conforming because the common block is not declared 
local to the subroutine that refers to it:

\fnexample{threadprivate}{3}

The following example is a correct rewrite of the previous example:

\fnexample{threadprivate}{4}

The following is an example of the use of \kcode{threadprivate} for local variables:
\topmarker{Fortran}

\fnexample{threadprivate}{5}

The above program, if executed by two threads, will print one of the following 
two sets of output: 

\pout{a = 11 12 13}
\\
\pout{ptr = 4}
\\
\pout{i = 15}

\pout{A is not allocated}
\\
\pout{ptr = 4}
\\
\pout{i = 5}

or

\pout{A is not allocated}
\\
\pout{ptr = 4}
\\
\pout{i = 15}

\pout{a = 1 2 3}
\\
\pout{ptr = 4}
\\
\pout{i = 5}

The following is an example of the use of \kcode{threadprivate} for module variables:
\topmarker{Fortran}

\fnexample{threadprivate}{6}
\end{fortranspecific}

\begin{cppspecific}
The following example illustrates initialization of \kcode{threadprivate} variables 
for class-type \ucode{T}. \ucode{t1} is default constructed, \ucode{t2} is constructed 
taking a constructor accepting one argument of integer type, \ucode{t3} is copy 
constructed with argument \ucode{f()}:

\cppnexample{threadprivate}{4}

The following example illustrates the use of \kcode{threadprivate} for static 
class members. The \kcode{threadprivate} directive for a static class member must 
be placed inside the class definition.

\cppnexample{threadprivate}{5}
\end{cppspecific}

