Tuesday, December 24, 2013

SMP as easy as you cannot imagine

In contrast to MPP where MPI is a standard, in the world of SMP pthreads are de facto standard way to make your program execute in parallel. But there is another standard, OpenMP.
test_parallel.c
#include <stdio.h>
#include <unistd.h>

#ifdef _OPENMP
  #include <omp.h>
#else
  #define omp_get_thread_num() 0
#endif


int main(int argc, char *argv) {
  int n = 10;
  int i;
  
  #pragma omp parallel
  {
    printf("thread %d\n", omp_get_thread_num());

    #pragma omp for
    for (i = 1; i <= n; i++ ) {
      sleep(1);
    }
  }
}
Test
gcc test_parallel.c
time ./a.out 
thread 0

real    0m10.002s
user    0m0.000s
sys     0m0.001s
Enable OpenMP
gcc -fopenmp test_parallel.c
time ./a.out 
thread 3
thread 7
thread 0
thread 4
thread 1
thread 5
thread 6
thread 2

real    0m2.002s
user    0m0.009s
sys     0m0.004s

No comments:

Post a Comment