2011-12-24 23 views
7

循環我有一個for循環在我的C代碼如下:並行化在C

for(i=0; i<100000; i++){ 

    a[i] = simulate(); // simulate() function simulates some system 

} 

我們看到,每次迭代的計算是從別人獨立(在a[]元素的順序並不重要我)。我想使用多線程並行化這個for循環的計算。我不完全知道如何在C中做到這一點?我有一個8處理器的機器,所以我可以並行運行8個線程。

回答

11

在C *中沒有可移植的方式來執行並行操作。然而,OpenMP standard的廣泛支持:

#pragma omp parallel for 
for(i=0; i<100000; i++){ 

    a[i] = simulate(); // simulate() function simulates some system 

} 

取決於你的編譯器,也將是你必須設置爲啓用OpenMP支持一個標誌:

  • MSVC:/openmp
  • GCC :-fopenmp

以及一個頭,如果你想訪問某些OpenMP的功能:

#include <omp.h> 

編輯:

*(非常最近批准)C11標準有通過<threads.h>線程的支持。

+1

'有沒有便攜的方式來做C#中的並行性新的標準C11現在只有幾天的時間了,但這種情況正在改變! – u0b34a0f6ae 2011-12-24 19:22:53

+0

@ kaiser.se哇,我沒有意識到C11被批准了!我會在我的回答中提到這一點。謝謝! – Mysticial 2011-12-24 19:24:29

+0

感謝您的回覆。我試過這個。對於某些[我]我得到一個「南」或「 - 南」,雖然代碼連續執行時正常工作。我認爲可能有某種同步問題 – 2011-12-26 15:52:01

0

如果你的編譯器支持C11標準,特別是stdatomic.h那麼你可以這樣做。

下面是一個粗略的例子,應該給你它背後的基本想法。這不是很難。這個使用posix線程,但你應該能夠使用任何線程庫。

#include <stdio.h> 
#include <stdatomic.h> 
#include <pthread.h> 

#define ELEMENTS_N 500000 

_Atomic unsigned int x; 
unsigned int N; 
unsigned int anyArray[ELEMENTS_N]; 

void * ThreadLoop (void * args) 
{ 
    unsigned int l; 
    while((l = atomic_load(&x)) < N) 
    { 
    if (atomic_compare_exchange_weak(&x, &l, l + 1)) 
    { 
     anyArray[l] = l; 
    } 
    } 
    return 0; 
} 


int main (int argc, char *argv[]) 
{ 

    pthread_t th1; 
    pthread_t th2; 
    int v; 

    atomic_store(&x, 0); 
    N = ELEMENTS_N; 

    v = pthread_create(&th1, NULL, &ThreadLoop, NULL); 
    v = pthread_create(&th2, NULL, &ThreadLoop, NULL); 

    pthread_join(th1, NULL); 
    pthread_join(th2, NULL); 

    for(v = 0; v < ELEMENTS_N; v++) 
    { 
    printf("%d ", anyArray[v]); 
    } 

    return 0; 
}