参考:
通过 GCC 学习 OpenMP 框架 (详细,我只看到临界区之前)
OpenMP基本概念 (全看,内含并行化控制的三种编程要素:编译制导、API函数集和环境变量)
OpenMP入门教程(一)(也讲了fork-join执行模型、线程概念、数据作用域...)
我主要跟着第一篇教程看了部分内容,后面两篇当作补充,这里po一下我打的两个简单例子:
test1.cpp
#include <iostream>
int main()
{
#pragma omp parallel
{
std::cout << "Hello World!
";
}
}
我的虚拟机设置的双核
test2.cpp
#include <omp.h>
#include <math.h>
#include <time.h>
#include <iostream>
int main()
{
int i, nthreads;
clock_t clock_timer;
double wall_timer;
double c[1000000];
for (nthreads = 1; nthreads <= 2; ++nthreads) {
clock_timer = clock();
wall_timer = omp_get_wtime();
#pragma omp parallel for private(i) num_threads(nthreads)
for (i = 0; i < 10; i++)
{
c[i] = sqrt(i * 4 + i * 2 + i);
std::cout<<" i: "<<i<<" thread_number: "<<omp_get_thread_num()<< std::endl;
}
std::cout << "
threads: " << nthreads << " time on clock(): " <<
(double) (clock() - clock_timer) / CLOCKS_PER_SEC
<< " time on wall: " << omp_get_wtime() - wall_timer <<"
";
}
}