什么时候应该使用 OpenMP 库?

发布于 2024-10-31 09:38:59 字数 205 浏览 0 评论 0原文

据我了解,OpenMP是一个标准,也是一个在C++代码中实现多线程的库。

Visual C++ 已经具有用于 Windows 的线程 API,UNIX 具有 POSIX 线程。我不明白为什么需要它,或者什么场景适合使用OpenMP。

编辑:与使用 CreateThread 或其他 POSIX 函数相比,OpenMP 是否也提高了性能(假设类似的代码被并行化)?

As I understand, OpenMP is a standard and also a library to implement multi-threading in C++ code.

Visual C++ already has threading APIs for Windows, and UNIX has POSIX threading. I don't undertand why it is required, or in which scenario it is applicable to use OpenMP.

EDIT : Does OpenMP has improved performance too, in comparision to using CreateThread or other POSIX functions (assuming similar code was parellilized)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

つ低調成傷 2024-11-07 09:38:59

系统线程 API(例如 POSIX 线程)要求您手动执行大量工作(设置线程、在线程之间分配工作、完成时同步、拆除线程等)。大量的代码膨胀掩盖了您真正想要做的事情。并且容易出错。而且很乏味。并且依赖于平台。

OpenMP 会为您完成这一切。在我看来,它最适合数据并行;在许多情况下,就像在 for 循环之前放置 #pragma omp 指令一样简单,该循环将自动成为多线程。但它也可以用于任务并行。

OpenMP 不会提高性能,因为始终可以编写至少与 OpenMP 版本一样好的手动线程代码。但通常情况下,只需 5 分钟的编码工作,OpenMP 就能为您带来 90% 以上的理论最佳性能(假设您一开始就以线程友好的方式编写了循环)。

我建议阅读维基百科文章以获取一些很好的示例。

System threading APIs (such as POSIX threads) require you to do an awful lot of work manually (setting up the threads, splitting up the work between the threads, synchronising when they are complete, tearing down the threads, etc.). Lots and lots of code bloat that obscures what you're really trying to do. And error-prone. And tedious. And platform-dependent.

OpenMP does all of this for you. In my opinion, it's most suitable for data-parallelism; in many cases, it's as simple as putting a #pragma omp directive before e.g. a for loop, and that loop will be automatically multi-threaded. But it can also be used for task-parallelism as well.

OpenMP doesn't improve performance, in the sense that it's always possible to write manual threading code that performs at least as well as the OpenMP version. But very often, OpenMP will get you 90%+ of theoretical optimum performance, with 5 minutes of coding effort (assuming you have written your loops in a thread-friendly way in the first place).

I recommend reading the Wikipedia article for some good examples.

春风十里 2024-11-07 09:38:59

例如,当您尝试编写可移植代码时。 OpenMP 可在 Windows 和 UNIX 系统上运行。
此外,大多数时候它比操作线程更容易使用。

When you're trying to do a portable code for example. OpenMP works both on windows and unix systems.
Moreover, it's most of the time a lot easier to use than manipulating threads.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文