如何在 OpenMP 中使用锁?
我有两段 C++ 代码在 2 个不同的内核上运行。他们都写入同一个文件。
如何使用OpenMP并确保不崩溃?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要
OMP_SET_LOCK
/OMP_UNSET_LOCK
函数:https://hpc.llnl.gov/tuts/openMP/#OMP_SET_LOCK
基本上:
尽管具体的 API 调用不同,但大多数锁定例程(例如 pthreads 信号量和 sysv 信号量)都适用于此类逻辑。
You want the
OMP_SET_LOCK
/OMP_UNSET_LOCK
functions:https://hpc.llnl.gov/tuts/openMP/#OMP_SET_LOCK
Basically:
Most locking routines such as pthreads semaphores and sysv semaphores work on that sort of logic, although the specific API calls are different.
为了后来者的利益,使用关键是另一种选择。您甚至可以创建命名的关键部分。
例如:
编辑:Victor Eijkhout 发起的评论中有一个很棒的线索。总结和释义:简而言之,关键性锁定了一个代码段。在更复杂的示例中,您只想锁定特定的数据项,这可能有点过分了。在这两种方法之间做出选择之前,了解这一点很重要。
For the benefit of those coming after, using
critical
is another option. You can even make named critical sections.For example:
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.