Reputation: 557
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.
Upvotes: 17
Views: 21715
Reputation: 317
// Finding minimum in a set using parallel CPU
int j,k;
double val_glob=1;
double val, valmin;
for (k=0; k<100; k++) {
// This j-loop should run in parallel and each thread pick its own part of the k-values from the k-loop
valmin=1;
for (j=0; j<100000; j++)
val=sin((double)k)*sin((double)j);
if (val<valmin) {
valmin=val;
};
};
// This should run in serial
if (valmin<val_glob) {
val_glob=valmin;
}
// Here if k-loop is not finished next thread should start it again always with different k-value.
};
printf("Minimum is: %g\n",val_glob);
Upvotes: -1
Reputation:
If your compiler supports the C11 standard, specifically stdatomic.h
then you can do this.
Below is a crude example that should give you the basic idea behind it. It's not very hard. This one uses posix threads but you should be able to use any threading 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;
}
Upvotes: 2
Reputation: 471289
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>
.
Upvotes: 18