I have a loop executed on multiple threads. Each loop will store a value into a global vector. The vector index variable is used by all threads and each thread increments the index after vector update. The access to the index must be protected. How the protection is done in OpenMP?
1/ If I specify #pragma omp parallel shared(k) Will this protect (synchronize access to) k-index access across threads?
int k = 0;
#pragma omp parallel shared(k)
for (int i = 1; i < d; ++i)
{
for (int j = 0; j < i; ++j)
{
my_vec[k++] = some_value; //no need to protect my_vector, if k is unique across trheads
}
}
2/ Do I need to use critical section
int k = 0;
#pragma omp parallel
for (int i = 1; i < d; ++i)
{
for (int j = 0; j < i; ++j)
{
#pragma omp critical (section_name)
{
my_vec[k++] = some_value;
}
}
}
3/do I need to use both, the shared clause and critical section block?