OpenMP is your friend

4. October 2006 08:42 by Jaguilar in General  //  Tags: ,   //   Comments (0)

OpenMP is very easy-to use API that you can use to very rapidly add multi-threading to your C/C++ applications. OpenMP allows you to parallelize the execution of a region of code by just adding a few pragmas to the code. For example, take this code:

   for(int i = 0;i<=100;i++){
       a[i] = a[i]*10;
       ...
   }

The code above performs a for loop sequentially. Since each iteration could be executed independently, we can easily add multi-threading to the application by adding these simple pragmas:

#pragma omp parallel for
   for(int i = 0;i<=100;i++){
       a[i] = a[i]*10;
       ...
   }

The omp pragmas tell the compiler to generate code to parallelize the execution of the for loop. That means that if you run this code on a 4 core machine, it will create 4 threads, and each one will execute 25 iterations of the loop. Just by adding those pragmas, you now have a multi-threaded application that takes advantage of multi-core systems.

Yes, it's that simple.

Categories