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 the calculation of each iteration is independent of the others (the order of the elements in a[] is not important to me). I want to parallelize the calculation of this for loop using multithreading. I don’t know exactly how to do this in C? I have an 8-processor machine, so I can run 8 threads in parallel.

+7
source share
2 answers

In C * there is no portable way to do parallelism. 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, a flag will be set that must be enabled to support OpenMP:

  • MSVC: /openmp
  • GCC: -fopenmp

as well as the title if you want to access some OpenMP features:

 #include <omp.h> 

EDIT:

* (recently approved) C11 standard supports threads through <threads.h> .

+11
source

If your compiler supports the C11 standard, in particular stdatomic.h , you can do this.

The following is a rough example that should give you the basic idea. It is not very difficult. This one uses posix streams, but you should be able to use any stream library.

 #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; } 
0
source

All Articles