代码改变世界

OpenMP的hello world

2011-04-04 10:59  会被淹死的鱼  阅读(652)  评论(0编辑  收藏  举报
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <omp.h>
4
5  int main(int argc, char *argv[])
6 {
7 int threadID, totalThreads;
8 omp_set_num_threads(4);
9
10 #pragma omp parallel private(threadID)
11 {
12 threadID = omp_get_thread_num();
13 printf("\nHello World is from thread %d\n", (int) threadID);
14
15 if (threadID ==0) {
16 printf("\nMaster thread being called\n");
17 totalThreads = omp_get_num_threads();
18 printf("Total number of threads are %d\n", totalThreads);
19 }
20 }
21
22 return 0;
23 }

OpenMP是一种可移植的多线程解决方案,支持Fortran、C和C++,提供了一组与平台无关的编译指导(pragmas)、指导命令(directive)、函数调用和环境变量,可以显示地指导编译器如何以及何时利用应用程序中的并行性。它为编写多线程程序提供了一种简单的方法,而无需程序员进行复杂的线程创建、同步、负载平衡和销毁工作。

在gcc下编译openmp的程序,保存为hello.c

1 #include <stdio.h>
2 #include <omp.h>
3
4 int main(int argc, char *argv[])
5 {
6 #pragma omp parallel
7 printf("Hello, World!\n");
8 }

编译方法,需要添加编译选项-fopenmp

1 gcc -fopenmp -o hello hello.c

在terminal中运行

./hello

可以看到输出为

Hello, World!
Hello
, World!

测试环境:ubuntu 10.04, gcc 4.4.3