一、简介
OpenMP (Open Multi-Processing) 是一个用于并行编程的应用程序接口(API),它支持多平台共享内存的多线程并行化。本文介绍了如何在CMake项目中使用OpenMP进行并行加速。
二、在CMake项目中使用OpenMP
1. 在CMakeLists.txt中添加OpenMP库
CMakeLists.txt
代码:
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 14)
project(learn_openmp)
include_directories(include)
# 搜索 OpenMP 库
find_package(OpenMP REQUIRED)
file(GLOB project_file main.cpp)
add_executable(${PROJECT_NAME} ${project_file})
# 链接 OpenMP 库
if(OpenMP_CXX_FOUND)
target_link_libraries(${PROJECT_NAME} PUBLIC OpenMP::OpenMP_CXX)
endif()
main.cpp
代码:
#include <omp.h>
#include <iostream>
int main()
{
// 设置使用的 线程数
omp_set_num_threads(8);
#pragma omp parallel // 构造一个并行块
{
int thread_id = omp_get_thread_num(); // 获取当前线程id
std::cout << "Hello from thread " << thread_id << std::endl;
}
return 0;
}
可能的运行结果:
Hello from thread Hello from thread Hello from thread Hello from thread 235
Hello from thread
Hello from thread 0
4
Hello from thread 7
Hello from thread 1
6
三、OpenMP样例
1. 并行执行代码块
#include <omp.h>
#include <iostream>
int main()
{
omp_set_num_threads(8);// 设置使用的线程数为 8
#pragma omp parallel // 构造一个并行块,该线程块内的代码会被并行的运行 8 次
{
int thread_id = omp_get_thread_num(); // 获取当前线程id
std::cout << "Hello from thread " << thread_id << std::endl;
}
return 0;
}
2. 并行执行 for 循环
#include <omp.h>
#include <iostream>
int main()
{
// 设置使用的 线程数
omp_set_num_threads(8);
/* 1.第一种并行for循环方法 */
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < 10; i++)
{
std::cout << "i:" << i << " thread_id:" << omp_get_thread_num() << ";\n";
}
}
std::cout << "======================\n";
/* 2.第二种并行for循环方法 */
#pragma omp parallel for
for (int j = 0; j < 10; j++)
{
std::cout << "j:" << j << " thread_id:" << omp_get_thread_num() << ";\n";
}
return 0;
}
三、参考
[1].学习openmp-cmake配置
[2].OpenMP简易教程