How to use lock in OpenMP?

MainID picture MainID · Mar 7, 2010 · Viewed 52.5k times · Source

I have two pieces of C++ code running on 2 different cores. Both of them write to the same file.

How to use OpenMP and make sure there is no crash?

Answer

user257111 picture user257111 · Mar 7, 2010

You want the OMP_SET_LOCK/OMP_UNSET_LOCK functions: https://computing.llnl.gov/tutorials/openMP/#OMP_SET_LOCK. Basically:

omp_lock_t writelock;

omp_init_lock(&writelock);

#pragma omp parallel for
for ( i = 0; i < x; i++ )
{
    // some stuff
   omp_set_lock(&writelock);
    // one thread at a time stuff
    omp_unset_lock(&writelock);
    // some stuff
}

omp_destroy_lock(&writelock);

Most locking routines such as pthreads semaphores and sysv semaphores work on that sort of logic, although the specific API calls are different.