2015-09-11 18 views
1

我是OpenMP的新手,我想製作多線程程序。所以我的txt文件C++ OpenMP每個線程從私有結構對象打印

London 2 
A 
B 
Miami 3 
C 
D 
E 

當我閱讀我的文件,我把我所有的數據爲struct稱爲LetterStruct

struct LetterStruct{ 
    string city; 
    int nr; 
    string letters[ARRAY_SIZE]; 
}; 

我想打印我的數據像這樣的(我知道該訂單將每個我運行我的程序時)

thread_0 A 
thread_0 B 
thread_1 C 
thread_1 D 
thread_1 E 

所以每個線程應打印城市的字母之一(例如線程0應打印倫敦和線程1 PR應該是不同的INT邁阿密字母)

所以在這裏我做了什麼

void setUpThreads(int arraySize) { 
    LetterStruct letter; 
    omp_set_num_threads(2); // number of threads 2 (because 2 Miami and London) 
    for (int j = 0; j < 1; j++) { 
     #pragma omp parallel private(letter) 
     { 
      int id = omp_get_thread_num(); 
      letter = letterArray[j]; // get struct info 
      for (int i = 0; i < ARRAY_SIZE; i++) { 
       cout << "thread_" << id << " " << letter.letters[i] << endl; 
      } 
     } 
    } 
} 

這是我的結果

thread_0 thread_1 A 
A 
thread_0 thread_1 B 
B 
thread_0 thread_1 C 
thread_1 C 
thread_0 thread_1 D 
thread_1 D 
thread_0 thread_1 E 
thread_1 E 

看來,這兩個線程都邁阿密和倫敦文字信息(但我做了這個private(letter))和出於某種原因,一切都打印不正確...所以我錯過了什麼?

回答

2

目前,您的線程正在複製工作。也就是說,他們都在做同樣的事情。 #pragma omp parallel所做的是告訴代碼在每個線程的括號內完成所有操作。這不是你想要它做的。而應將#pragma omp parallel private(letter)替換爲for循環上方的#pragma omp parallel for private(letter)。這會告訴你的代碼將循環的每次迭代分解爲不同的線程。

+0

謝謝,但我早些時候嘗試過,並且我得到了'預期for循環openmp'並行'directive' – David

+0

當你在'for'循環之前放置時,你會得到那個嗎?那個錯誤信息沒有任何意義,因爲你在'parallel for'指令後面有'for'循環。你確定你沒有把#pragma放在錯誤的地方嗎? –

+0

我把'#pragma omp parallel for private(letter)'for first for for循環for(int j = 0; j <1; j ++)'並且我得到這個錯誤 – David