2011-12-24 58 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; 
}