It Just Works (In Parallel)

I just have to point out this little snippet because it's one of those rare it just works experiences when you can solve a complex problem with a single line of code.

I'm toying with some ray tracing code, one of the classic hackers playgrounds.  Ray traced images can take a long time to render and I have a pretty modern machine so I wanted to make best use of my dual CPUs.  I began with a loop that looked like this:

    for(int x = 0; x < bitmap.Width; x++)

    {

        RenderLine(x);

    }

While the rendering is in progress you can see the image gradually filled in from left to right.  Pretty simple but writing the code to divide the loop up into sensible pieces and distribute it to a pool of threads was going to be more work than the actual ray tracing itself.  Fortunately I happened upon the Parallel Extensions library which let me implement all of the above by referencing a .dll and changing a single line of code:

    Parallel.For(0, bitmap.Width, (x) =>

    {

        RenderLine(x);

    }

Now that's magic.  Rather than rendering the image one line at a time the library has decided that 4 threads would be optimal for my dual CPU configuration and chunked the work accordingly.  The image below is taken part way through a render and shows that the loop has been broken into segments of about 20 pixels each:

003

Now I have more time to spend sorting out the horrible colours on that sphere!  There are a couple of things I should mention before closing:

  • You still need to be careful not to block the UI thread for any length of time.
  • At some point you have to combine the results back into a single thread so you can output the image.
  • Ray tracing is an ideal candidate for parallelism as each pixel can be rendered independently of any other but chances are your application is going to be a little trickier.
  • The library is still a CTP so the usual warnings about pre release software apply.
  • Immutable state is your friend.

There is a good amount of advice in the documentation that comes with the library and a number of articles online if you want to know more.

Labels: ,

26/08/2008 03:37 AM (UTC -07:00)