Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallelizing a for loop in C

I have a for loop in my C code as follows:

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

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

}

We see that computation of each iteration is independent from others (the order of elements in a[] is not important to me). I want to parallelize the computation of this for loop using multi-threading. I am not exactly aware of how to do this in C? I have a 8 processor machine, so I can run 8 threads parallely.

like image 566
RIchard Williams Avatar asked Dec 24 '11 19:12

RIchard Williams


1 Answers

There's no portable way to do parallelism in C*. However, the OpenMP standard is widely supported:

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

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

}

Depending on your compiler, there will be a flag that you must set to enable OpenMP support:

  • MSVC: /openmp
  • GCC: -fopenmp

as well as a header if you wish to access certain OpenMP functions:

#include <omp.h>

EDIT :

*The (very recently approved) C11 standard has support for threads via <threads.h>.

like image 51
Mysticial Avatar answered Oct 26 '22 06:10

Mysticial