How to use lock in OpenMP?

徘徊边缘 提交于 2019-11-26 06:39:37

问题


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?


回答1:


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.




回答2:


For the benefit of those coming after, using critical is another option. You can even make named critical sections.

For example:

#include <omp.h>

void myParallelFunction()
{
    #pragma omp parallel for
    for(int i=0;i<1000;++i)
    {

        // some expensive work 

        #pragma omp critical LogUpdate
        {
            // critical section where you update file        
        }

        // other work

        #pragma omp critical LogUpdate
        {
            // critical section where you update file      
        }
    }
} 

Edit: There's a great thread in the comments initiated by Victor Eijkhout. Summarizing and paraphrasing: In short critical locks a code segment. That can be overkill in more complex examples where all you want to do is lock a specific data item. It's important to understand this before you make a choice between the two methods.




回答3:


#pragma omp critical
{
    // write to file here
}


来源:https://stackoverflow.com/questions/2396430/how-to-use-lock-in-openmp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!