Friday, August 17, 2012

Parallel Programming with the C++ AMP library

Microsoft's C++ AMP library is a group of language extensions that allow your C++ code to take advantage of the mulitple cores on a GPU. The new code works seamlessly with existing code and makes it easy to increase the parallelism of your programs. The library comes with code for features such as arrays, memory transferring and mathematical functions. To use it, you wil first need a copy of visual Studio 2012 which at present can be downloaded for free as a release candidate. The libraries automatically come installed with it.

Once you have visual Studio up and running you can begin. Simply create an empty Win32 console application under the Visual C++ project types. Create a .cpp file to hold your main function. To make use of the code you simply need to include the amp.h header file in your code. We'll start with just a simple loop that will modify an array in parallel.

Microsoft gives you two data structures for modifying data in parallel, array and array_view. Here we will copy elements in to an array_view so we can act on them.

Now we will loop through all three members and add 10 to them.

This code loops three times in parallel, adding 10 to each threads part of the array. Now we can copy the data back to a vector and display the results.

The final code looks like this.

And that's it for this simple intro. There's plenty more to explore though.