如何使用OpenMP的#pragma指令创建独立线程分段处理数值迭代任务
OpenMP 可运行实现代码
可均等划分总迭代数50的线程数
50的所有正约数均可:1、2、5、10、25、50
公共依赖&编译命令
#include <iostream> #include <omp.h> using namespace std; // 示例Foo函数,可自定义逻辑、返回值类型 inline int Foo(int p = 0) { // 此处替换为实际业务逻辑 return p * 2; }
编译命令:g++ 代码文件名.cpp -o 可执行文件名 -fopenmp
场景1:5线程分段迭代p(总迭代50次)
int main() { const int total_iteration_size = 50; const int thread_num = 5; omp_set_num_threads(thread_num); #pragma omp parallel { int tid = omp_get_thread_num(); int per_thread_cnt = total_iteration_size / thread_num; int range_start = tid * per_thread_cnt; int range_end = (tid + 1) * per_thread_cnt - 1; int p = range_start; while (p <= range_end) { // 替换为实际迭代逻辑 std::cout << "线程" << tid << " 迭代值p=" << p << std::endl; p++; } } return 0; }
场景2:3线程均等调用Foo函数(总调用30次)
int main() { const int total_call_cnt = 30; const int thread_num = 3; omp_set_num_threads(thread_num); #pragma omp parallel { int tid = omp_get_thread_num(); int per_thread_call = total_call_cnt / thread_num; int cnt = 0; while (cnt < per_thread_call) { int res = Foo(); std::cout << "线程" << tid << " 第" << cnt + 1 << "次调用Foo 返回值=" << res << std::endl; cnt++; } } return Foo(); }
场景3:2线程先迭代p、再传参调用Foo(总迭代20次,总调用20次)
int main() { const int total_cnt = 20; const int thread_num = 2; omp_set_num_threads(thread_num); int final_res; #pragma omp parallel { int tid = omp_get_thread_num(); int per_thread_cnt = total_cnt / thread_num; int range_start = tid * per_thread_cnt; int range_end = (tid + 1) * per_thread_cnt - 1; // 第一步:分段迭代p int p = range_start; while (p <= range_end) { std::cout << "线程" << tid << " 迭代值p=" << p << std::endl; p++; } // 第二步:分段传参调用Foo p = range_start; int cnt = 0; while (cnt < per_thread_cnt) { int res = Foo(p); std::cout << "线程" << tid << " 调用Foo(" << p << ") 返回值=" << res << std::endl; p++; cnt++; } } final_res = Foo(20); std::cout << "最终调用Foo返回值:" << final_res << std::endl; return final_res; }
内容的提问来源于stack exchange,提问作者AncientTides
相关产品推荐
相关产品推荐

