C++ 如何在 OpenMP 中使用锁?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2396430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use lock in OpenMP?
提问by MainID
I have two pieces of C++ code running on 2 different cores. Both of them write to the same file.
我有两段 C++ 代码在 2 个不同的内核上运行。它们都写入同一个文件。
How to use OpenMP and make sure there is no crash?
如何使用 OpenMP 并确保没有崩溃?
回答by
You want the OMP_SET_LOCK
/OMP_UNSET_LOCK
functions: https://computing.llnl.gov/tutorials/openMP/#OMP_SET_LOCK. Basically:
您需要OMP_SET_LOCK
/OMP_UNSET_LOCK
功能:https://computing.llnl.gov/tutorials/openMP/#OMP_SET_LOCK。基本上:
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.
尽管特定的 API 调用不同,但大多数锁定例程(例如 pthreads 信号量和 sysv 信号量)都适用于这种逻辑。
回答by Chris A.
For the benefit of those coming after, using critical
is another option. You can even make named critical sections.
为了后来者的利益,使用critical
是另一种选择。您甚至可以创建命名的临界区。
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.
编辑:Victor Eijkhout 发起的评论中有一个很好的线索。总结和释义:简而言之就是critical
锁定一个代码段。在更复杂的示例中,您要做的只是锁定特定数据项,这可能有点过头了。在这两种方法之间做出选择之前,了解这一点很重要。
回答by adamax
#pragma omp critical
{
// write to file here
}