When should the OpenMP library be used?
As I understand, OpenMP is a standard and also a library to implement multi-threading in C++ code.
Visual C++ alread开发者_JS百科y 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)?
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.
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.
精彩评论