0
votes

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?

1
Aren't you missing an omp parallel in that?Shawn
Ah the whole thing is inside a #pragma omp parallel blockGyakenji
@Gyakenji Maybe put the lock initialisation outside of the parallel block?RmbRT
The whole thing? Including the definition of the lock variable? Yeah, that'd be a problem because that makes them private ones, not shared...Shawn
@Shawn Ahh yes, that makes sense. It works now, thanks!Gyakenji

1 Answers

2
votes

Careless mistake: defining lock should be outside parallel block