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.
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:
/openmp
-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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With