gcc对OpenMP的支持

OpenMP是专门针对共享地址空间的并行计算机提供的并行计算库,在Intel C++和Visual C++ 8.0里通过#pragma支持。用OpenMP,可以不必去写诸如CreateThread之类的线程管理代码,多线程程序写起来比较简洁。而且 OpenMP提供了很丰富的指令,对于同步共享变量、合理分配负载等任务,都提供了有效的支持。不过因为这个东西用起来很轻松,稍一疏忽就能 酿成愚蠢错误,所以肯定是要经常用才能驾驭好的。
在GCC编译时使用OpenMP特性,需要加上“-fopenmp"参数
gcc -fopenmp test_omp.c
g++ -fopenmp test_omp.cc
gfortran -fopenmp test_omp.f90(95)

程序一:main.c

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
void Test (int n) {
int i;
for (i = 0; i < 10000; ++i)
{
//do nothing, just waste time
}
printf("%d, ", n);
}
int main(int argc, char* argv[]) {
int i;

#pragma omp parallel for
for (i = 0; i < 10; ++i)
Test( i );
return 1;
}

编译执行:
[ycdoit@ycdoit Lu]$ gcc -fopenmp main.c -o main.out
[ycdoit@ycdoit Lu]$ ./main.out
0, 5, 1, 6, 2, 3, 4, 7, 8, 9,


程序二:OpenMp版本的Hello Word

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
int nthreads,tid;
// fork a team of thread
#pragma omp parallel private(nthreads,tid)
{
//obtian and print thread id
tid=omp_get_thread_num();
printf("Hello Word from OMP thread %d\n",tid);

// only master thread does this;
if(tid==0)
{
nthreads = omp_get_num_threads();
printf("Number of thread: %d\n",nthreads);
}
}
return 0;
}

编译执行:
[ycdoit@ycdoit Lu]$ gcc -fopenmp main.c -o main.out
[ycdoit@ycdoit Lu]$ ./main.out
Hello Word from OMP thread 0
Number of thread: 2
Hello Word from OMP thread 1
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值