openmp并行for循环里调用函数会出错吗???会出现数据竞争吗???
希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10581430.html
不知道你这个问题是否已经解决, 如果还没有解决的话://串行执行for循环
#include <iostream>
#include <omp.h>
void test()
{
int a = 0;
for (int i=0;i<100000000;i++)
a++;
}
int main()
{
double time = omp_get_wtime();
//利用omp_get_wtime()函数可以测量执行的时间,单位秒
for (int i=0;i<8;i++)
test();
std::cout<<"time = "<< omp_get_wtime()-time << " seconds"<< std::endl;
}
运行结果如下:
[root@red-hat f]# g++ time.cpp -fopenmp
[root@red-hat f]# ./a.out
time = 1.75524 seconds
下面在main函数中,用“ #pragma omp parallel for ”把上面的编程并行执行
//利用OpenMP并行执行for循环
#include <iostream>
#include <omp.h>
void test()
{
int a = 0;
for (int i=0;i<100000000;i++)
a++;
}
int main()
{
double time = omp_get_wtime();
//利用omp_get_wtime()函数可以测量执行的时间,单位秒
#pragma omp parallel for //将下面的for循环并行执行
for (int i=0;i<8;i++)
test(); //多个线程并行执行test()
std::cout<<"time = "<< omp_get_wtime()-time << " seconds"<< std::endl;
}
运行结果如下:
[root@red f]# g++ timeMP.cpp -fopenmp
[root@red f]# ./a.out
time = 0.276875 seconds
由运行结果可知,运行时间从1.755 秒减少到0.276秒,相比串行执行并行执行时间减少到近1/7,大大降低了运行的时间。
OpenMP for指示将C++ for循环的多次迭代划分给多个线程(划分指,每个线程执行的迭代互不重复,所有线程的迭代并起来正好是C++ for循环的所有迭代),这里C++ for循环需要一些限制从而能在执行C++ for之前确定循环次数,例如C++ for中不应含有break等。