Just My Life & My Work

[OpenMP] Hello World

學任何程式語言都要來Hello World,這裡OpenMP也不例外,在Microsoft Visual Studio 2010 Professional設定啟用OpenMP(可參考[OpenMP] Visual Studio 使用 OpenMP)之後,就可以編譯OpenMP的程式碼。

以下是使用「C語言」的程式碼:

/**
	Theme: OpenMP Hello World
	Compiler: Visual Studio 2010 Professional
	Date: 100/10/25
	Author: HappyMan
	Blog: https://cg2010studio.wordpress.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void Hello(void);  /* Thread function */

/*-----------------------------------------------------------------*/
int main() {
   int thread_count = 8;
#  pragma omp parallel num_threads(thread_count)
   Hello();

   system("pause");
   return 0;
}  /* main */

/*-------------------------------------------------------------------
 * Function:    Hello
 * Purpose:     Thread function that prints message
 */
void Hello(void) {
   int my_rank = omp_get_thread_num();
   int thread_count = omp_get_num_threads();

   printf("Hello from thread %d of %d\n", my_rank, thread_count);

}  /* Hello */

執行結果:

Hello from thread 2 of 8
Hello from thread 0 of 8
Hello from thread 3 of 8
Hello from thread 5 of 8
Hello from thread 4 of 8
Hello from thread 6 of 8
Hello from thread 1 of 8
Hello from thread 7 of 8
請按任意鍵繼續 . . .

以下是使用「C++」的程式碼:

/**
	Theme: OpenMP Hello World
	Compiler: Visual Studio 2010 Professional
	Date: 100/10/25
	Author: HappyMan
	Blog: https://cg2010studio.wordpress.com/
*/
#include <iostream>
#include <omp.h>
using namespace std;

void Hello(void);  /* Thread function */

/*-----------------------------------------------------------------*/
int main() {
   int thread_count = 8;
#  pragma omp parallel num_threads(thread_count)
   Hello();

   system("pause");
   return 0;
}  /* main */

/*-------------------------------------------------------------------
 * Function:    Hello
 * Purpose:     Thread function that prints message
 */
void Hello(void) {
   int my_rank = omp_get_thread_num();
   int thread_count = omp_get_num_threads();

   cout<<"Hello from thread "<<my_rank<<" of "<<thread_count<<endl;

}  /* Hello */

執行結果:

Hello from thread Hello from thread Hello from thread Hello from thread Hello fr
om thread Hello from thread Hello from thread Hello from thread 06245371 of  of
 of  of  of  of  of  of 88888888

請按任意鍵繼續 . . .

不一樣的地方在於輸出串流,C語言一氣呵成,把整個字串準備好之後再做輸出;而C++則分為五次輸出(「<<」有5次),CPU(我的是4核心)每執行完一次指令後即輸出,接著要再搶標準輸出串流。不過雖然是「搶」,但看一下輸出結果……thread似乎有排隊耶!這是巧合~

printf("Hello from thread %d of %d\n", my_rank, thread_count);
cout<<"Hello from thread "<<my_rank<<" of "<<thread_count<<endl;

若以單核心來執行以上兩行程式碼,列印順序一模一樣,但若是多核心的話,列印順序就是非決定性了。

所以之後我都用printf函式好了!

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲