Shared and
non-shared (private) variables
in OpenMP programs
- Similar to
Pthread programs,
an OpenMP has
2 different kinds of
variables:
-
Shared variables
where a
single copy of the
variable
exists and
all
threads
access the
same copy of the
variable
-
Non-shared
(a.k.a. "private") variables
where
each
threads
access its
own copy of the
variable
|
- Defining
shared and
non-shared
variables in
OpenNMP:
- By location:
- A variable
defined
outside
the parallel region is
shared
- A variable
defined
inside
the parallel region is
non-shared
|
- With keywords:
- A variable
defined as
shared(varName)
in the #pragma omp parallel are
shared
- A variable
defined as
private(varName)
in the #pragma omp parallel are
non-shared
|
|
|
Example of a
shared variable in
OpenMP
- Example of
using a
shared variable in
OpenMP:
int main(int argc, char *argv[])
{
int N; // Outside parallel region: shared
N = 1;
printf("Before parallel region: N = %d\n", N);
omp_set_num_threads(4);
#pragma omp parallel
{
for ( int i = 0; i < 10000; i++ )
N = N + 1; // Concurrent updates to a SHARED variable
}
printf("After parallel region: N = %d\n", N);
}
|
- Concurrent updates to
a
shared variable will
result in
"missed" updates
|
DEMO:
demo/OpenMP/shared-var.c
(gcc
-fopenmp shared-var.c)
Example of a
non-shared (private) variable in
OpenMP
- Example of
using a
non-shared (private) variable in
OpenMP:
int main(int argc, char *argv[])
{
int N; // Outside parallel region: shared
N = 7;
printf("Before parallel region: N = %d\n", N);
omp_set_num_threads(4);
#pragma omp parallel
{
int N = 1; // private (non-shared) variable
for ( int i = 0; i < 10000; i++ )
N = N + 1; // Updates to a NON-SHARED variable
printf("Inside parallel region: N = %d\n", N);
}
printf("After parallel region: N = %d\n", N);
}
|
-
Note:
there are
2 different variables named
N
used
in this OpenMP program !
|
DEMO:
demo/OpenMP/private-var.c
(gcc
-fopenmp private-var.c)
❮
❯