搜尋此網誌

2011年7月25日 星期一

OpenMP-shared for loop



#include <omp.h>
#include <iostream>
using namespace std;
int main() {
int n=10;
#pragma omp parallel shared(n)
{
#pragma omp for
for (int i=0; i<n; i++)
cout <<"Thread "<<omp_get_thread_num()<<" executes loop iteration "<< i<<endl;
}
return 0;
}



references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming

OpenMP-Parallel Constructor

Parallel constructor(平行結構):可以告訴compile,以下的程式碼要用parallel 的方式執行,
並且程式設計師也可以運用此結構,來個別定義thread的行為.
i.e.

#include <omp.h>
#include <iostream>
using namespace std;
int main() {
#pragma omp parallel
{
cout <<"The parallel region is executed by thread "<<omp_get_thread_num();
if (omp_get_thread_num() == 1) {
cout <<" Thread "<<omp_get_thread_num()<<" does things differently\n";
}
}
return 0;
}


附帶一提parallel region有兩種狀態:active以及inactive.
所謂的active是指有多個thread在執行運算,若只有一個thread在做運算的話就是inactive的狀態.


references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming

OpenMP conditional compilation

Conditional compilation is used to prevent unwanted results created from a non openmp compliant compiler .

Following is its format:

#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
//some code here
int TID = omp_get_thread_num();


references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming