0

How can I replace a critical section with omp_locks instead?

My original code with critical section is like this, which works fine:

#pragma omp for
for (int i = 0; i < n; i++){
    // do thread-safe pre-processing

    #pragma omp critical
    {
        // do critical section stuff
    }
}

Now I do the same thing but with locks instead:

omp_lock_t lock;
omp_init_lock(&lock);

#pragma omp for
for (int i = 0; i < n; i++){
    // do thread-safe pre-processing

    omp_set_lock(&lock);

    // do critical section stuff

    omp_unset_lock(&lock);
}
omp_destroy_lock(&lock);

But for some reason, I get the wrong result. Am I doing something wrong here?

Also, when I try to use multiple locks (e.g. for each element of array to write on), it seems to go into deadlock?

Gyakenji
  • 177
  • 1
  • 6

1 Answers1

2

Careless mistake: defining lock should be outside parallel block

Gyakenji
  • 177
  • 1
  • 6