Visual studio 2010 CTP并行编程: 分形绘图例子

http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c15649/Parallel-Programming-in-Visual-C-2010-CTP.htm


The CTP build of Visual C++ 2010 includes a new library to help you write native parallel code. Writing parallel code is getting more and more important with the broad availability of quad-core CPUs at this time and the many-core CPUs that will appear in the coming years. I will only be talking about the new concurrency library for native code. Of course, writing parallel code has already been possible for a long time. However, you had to create and manage all threads by yourself and this could often be a complex task. Because of this, it requires quite a bit of time to parallelize a simple loop over multiple threads. The new native concurrency library makes this much easier.

This article will explain the parallel_for construct that is part of the native concurrency library in more detail and will briefly touch on a few other constructs. For the example, I will parallelize a trivial implementation of a Mandelbrot fractal renderer.

A Simple Serial Mandelbrot Renderer

The code to render a Mandelbrot fractal looks like the following:

 
 
  1. int iHeight = rcClient.Height();
  2. int iHalfHeight = int(iHeight/2.0+0.5);
  3. int iWidth = rcClient.Width();
  4. int iHalfWidth = int(iWidth/2.0+0.5);
  5. int maxiter = 1024;
  6. // Position and size of our view on the imaginary plane
  7. double dView_r = 0.001643721971153;
  8. double dView_i = 0.822467633298876;
  9. CDC memDC;
  10. memDC.CreateCompatibleDC(&dc);
  11. CBitmap bmp;
  12. bmp.CreateCompatibleBitmap(&dc, iWidth, 1);
  13. CBitmap* pOldBmp = memDC.SelectObject(&bmp);
  14. for (int y=-iHalfHeight; y<iHalfHeight; ++y)
  15. {
  16. // Formula: zi = z^2 + z0
  17. double dZ0_i = dView_i + y * m_dZoomLevel;
  18. for (int x=-iHalfWidth; x<iHalfWidth; ++x)
  19. {
  20. double dZ0_r = dView_r + x * m_dZoomLevel;
  21. double dZ_r = dZ0_r;
  22. double dZ_i = dZ0_i;
  23. double d = 0.0;
  24. int iter;
  25. for (iter=0; iter < maxiter; ++iter)
  26. {
  27. double dZ_rSquared = dZ_r * dZ_r;
  28. double dZ_iSquared = dZ_i * dZ_i;
  29. if (dZ_rSquared + dZ_iSquared > 4)
  30. {
  31. // We escaped
  32. d = iter+1-log(log(sqrt(dZ_rSquared +
  33. dZ_iSquared)))/log(2.0);
  34. break;
  35. }
  36. dZ_i = 2 * dZ_r * dZ_i + dZ0_i;
  37. dZ_r = dZ_rSquared - dZ_iSquared + dZ0_r;
  38. }
  39.  
  40. memDC.SetPixel(x+iHalfWidth,0,RGB(d*50,d*50,d*50));
  41. }
  42. dc.BitBlt(0, y+iHalfHeight, iWidth, 1, &memDC, 0, 0, SRCCOPY);
  43. }
  44. memDC.SelectObject(pOldBmp);
  45. bmp.DeleteObject();
  46. memDC.DeleteDC();

This code first calculates the width and height of the window to which you will be rendering. It also sets up the position and size of your view on the imaginary plane. The renderer will render line by line in a memory device context, so you set up a memory device context and select a bitmap in it whose size is the width of the rendering window and whose height is just 1 pixel. Then, you loop over each line. In each line, you loop over each pixel and for each pixel you iterate a number of times to calculate the value of that pixel. When you escape from the Mandelbrot set, you calculate the value "d" to get some kind of smooth grayscale coloring of your fractal. Once a row has been rendered, it will be blitted to the screen using BitBlt so you can see the progress of the rendering.

When you would run this renderer, it will render line by line from top to bottom. A screenshot of this can be seen below:

Parallelizing the Mandelbrot Renderer

Before you can use the new native concurrency library, you need to include the ppl.h file. Also, these concurrency functions are inside the namespace Concurrency, so either use "using namespace Concurrency" or specify Concurrency in front of every use of something from the library.

 
 
  1. #include <ppl.h>
  2. using namespace Concurrency;

To parallelize the above Mandelbrot renderer using the new parallel_for construct from the Visual C++ 2010 CTP concurrency library, you basically only need to change the outer for loop—the loop that is iterating over all the rows. A first version would look like the following:

 
 
  1. int iHeight = rcClient.Height();
  2. int iHalfHeight = int(iHeight/2.0+0.5);
  3. int iWidth = rcClient.Width();
  4. int iHalfWidth = int(iWidth/2.0+0.5);
  5. int maxiter = 1024;
  6. // Position and size of our view on the imaginary plane
  7. double dView_r = 0.001643721971153;
  8. double dView_i = 0.822467633298876;
  9. parallel_for(-iHalfHeight, iHalfHeight,1,[&](int y){
  10. CDC memDC;
  11. CBitmap bmp;
  12. memDC.CreateCompatibleDC(&dc);
  13. bmp.CreateCompatibleBitmap(&dc, iWidth, 1);
  14. CBitmap* pOldBmp = memDC.SelectObject(&bmp);
  15. // Formula: zi = z^2 + z0
  16. double dZ0_i = dView_i + y * m_dZoomLevel;
  17. for (int x=-iHalfWidth; x<iHalfWidth; ++x)
  18. {
  19. double dZ0_r = dView_r + x * m_dZoomLevel;
  20. double dZ_r = dZ0_r;
  21. double dZ_i = dZ0_i;
  22. double d = 0.0;
  23. int iter;
  24. for (iter=0; iter < maxiter; ++iter)
  25. {
  26. double dZ_rSquared = dZ_r * dZ_r;
  27. double dZ_iSquared = dZ_i * dZ_i;
  28. if (dZ_rSquared + dZ_iSquared > 4)
  29. {
  30. // We escaped
  31. d = iter+1-log(log(sqrt(dZ_rSquared +
  32. dZ_iSquared)))/log(2.0);
  33. break;
  34. }
  35. dZ_i = 2 * dZ_r * dZ_i + dZ0_i;
  36. dZ_r = dZ_rSquared - dZ_iSquared + dZ0_r;
  37. }
  38.  
  39. memDC.SetPixel(x+iHalfWidth,0,RGB(d*50,d*50,d*50));
  40. }
  41. dc.BitBlt(0, y+iHalfHeight, iWidth, 1, &memDC, 0, 0, SRCCOPY);
  42. memDC.SelectObject(pOldBmp);
  43. bmp.DeleteObject();
  44. memDC.DeleteDC();
  45. });

The only things that have been changed in this code compared to the original code are the bold parts, meaning the "for" has been replaced with the "parallel_for" and the creation of the memory DC and bitmap are moved inside the parallel_for because you need a separate memory DC for every thread that will be created. The parallel_for construct is using another new feature of C++, called Lambda expressions, that allow you to create anonymous inline functions. Describing lambda expressions is outside the scope of this article.

Making the Renderer Thread Safe

When you would run the above code, you would notice that some lines will be missing in the rendering result. This is because you are writing to the same device context from different threads without any synchronization. To fix this, you will use a critical section to secure access to the device context so that only 1 thread can draw on it at the same time. The changes look as follows:

 
 
  1. int iHeight = rcClient.Height();
  2. int iHalfHeight = int(iHeight/2.0+0.5);
  3. int iWidth = rcClient.Width();
  4. int iHalfWidth = int(iWidth/2.0+0.5);
  5. int maxiter = 1024;
  6. // Position and size of our view on the imaginary plane
  7. double dView_r = 0.001643721971153;
  8. double dView_i = 0.822467633298876;
  9. // We need this critical section to have thread safe access to
  10. // our device context
  11. CRITICAL_SECTION cs;
  12. InitializeCriticalSection(&cs);
  13. parallel_for(-iHalfHeight, iHalfHeight,1,[&](int y){
  14. CDC memDC;
  15. CBitmap bmp;
  16. // We need to use a critical section here because we're
  17. // accessing our dc.
  18. EnterCriticalSection(&cs);
  19. memDC.CreateCompatibleDC(&dc);
  20. bmp.CreateCompatibleBitmap(&dc, iWidth, 1);
  21. LeaveCriticalSection(&cs);
  22. CBitmap* pOldBmp = memDC.SelectObject(&bmp);
  23. // Formula: zi = z^2 + z0
  24. double dZ0_i = dView_i + y * m_dZoomLevel;
  25. for (int x=-iHalfWidth; x<iHalfWidth; ++x)
  26. {
  27. double dZ0_r = dView_r + x * m_dZoomLevel;
  28. double dZ_r = dZ0_r;
  29. double dZ_i = dZ0_i;
  30. double d = 0.0;
  31. int iter;
  32. for (iter=0; iter < maxiter; ++iter)
  33. {
  34. double dZ_rSquared = dZ_r * dZ_r;
  35. double dZ_iSquared = dZ_i * dZ_i;
  36. if (dZ_rSquared + dZ_iSquared > 4)
  37. {
  38. // We escaped
  39. d = iter+1-log(log(sqrt(dZ_rSquared +
  40. dZ_iSquared)))/log(2.0);
  41. break;
  42.  
  43.  
  44. }
  45. dZ_i = 2 * dZ_r * dZ_i + dZ0_i;
  46. dZ_r = dZ_rSquared - dZ_iSquared + dZ0_r;
  47. }
  48.  
  49. memDC.SetPixel(x+iHalfWidth,0,RGB(d*50,d*50,d*50));
  50. }
  51. // We need to use a critical section here because we're
  52. // accessing our dc.
  53. EnterCriticalSection(&cs);
  54. dc.BitBlt(0, y+iHalfHeight, iWidth, 1, &memDC, 0, 0, SRCCOPY);
  55. LeaveCriticalSection(&cs);
  56. memDC.SelectObject(pOldBmp);
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65. bmp.DeleteObject();
  66. memDC.DeleteDC();
  67. });

Before starting the parallel_for loop, you initialize a critical section. Inside the parallel_for loop, you will wrap all usages of the device context "dc" inside EnterCriticalSection/LeaveCriticalSection constructs to make sure only 1 thread accesses that device context at the same time.

When executing this code, you will see that it is rendering in blocks, as can be seen in the following screenshot. Each block is being handled by a different thread.

This article comes with one attachment. MandelbrotPar_src.zip contains the above Mandelbrot example. In the toolbar of the application, you will find a button with a P in it. When you toggle this button, you will switch between serial and parallel rendering. The titlebar of the application shows the time it took to render the image in milliseconds. Please note that this is a very basic example application. The rendering is happening in the WM_PAINT handler directly, meaning it will redraw the entire fractal each time it needs to paint the window.

Parallel Programming in Visual C++ 2010 CTP

Other Concurrency Constructs

The native concurrency library also has some other high level constructs, such as parallel_for_each and parallel_invoke.

parallel_for_each

This construct can replace the std::for_each construct to iterate over a container in a parallel manner. An example could be a vector drawing application. The application might hold a vector of all objects that have to be rendered. When the application needs to render everything to the screen, it simply iterates over the vector and calls the Draw() functions on each object. For example:

 
 
  1. #include <algorithm>
  2. #include <vector>
  3.  
  4. class CObj
  5. {
  6. public:
  7. virtual void Draw();
  8. // ...
  9. }
  10.  
  11. class CObjRectangle : public CObj
  12. {
  13. public:
  14. virtual void Draw();
  15. // ...
  16. }
  17.  
  18. int main()
  19. {
  20. std::vector<CObj*> vec;
  21. // Add objects to this vector
  22. // ...
  23. // Draw all objects
  24. for_each(vec.begin(), vec.end(), [&](CObj* p) {
  25. if (p)
  26. p->Draw();
  27. });
  28. return 0;
  29. }

Automation for Innovation: Reducing Rework and Deployment Errors Through Release and Deployment Automation
Automation for Innovation: Reducing Rework and Deployment Errors Through Release and Deployment Automation
The above defines a base class for renderable objects and a specific rectangle class as an example. A vector is filled with renderable objects; then, the for_each construct will call the Draw() method on each object. This is happening in a serial way. You can simply parallelize this as follows:

 
 
  1. #include <ppl.h>
  2. using namespace Concurrency;
  3.  
  4. // ...
  5.  
  6. int main()
  7. {
  8. std::vector<CObj*> vec;
  9. // Add objects to this vector
  10. // ...
  11. // Draw all objects
  12. parallel_for_each(vec.begin(), vec.end(), [&](CObj* p) {
  13. if (p)
  14. p->Draw();
  15. });
  16. return 0;
  17. }

By simply replacing for_each with parallel_for_each, the loop is now being executed in parallel in several threads.

Note: This assumes that the Draw function will modify only a single object in each iteration.

parallel_invoke

parallel_invoke can be used to launch several functions, execute them in parallel, and wait until they are all finished. A simple example is shown below:

 
 
  1. #include <windows.h>
  2. #include <iostream>
  3. #include <ppl.h>
  4.  
  5. using namespace std;
  6. using namespace Concurrency;
  7.  
  8. int main()
  9. {
  10. parallel_invoke(
  11. [=]{for (int i=0; i<100; ++i)
  12. {cout << i << endl; Sleep(100);}},
  13. [=]{for (int i=0; i<10; ++i)
  14. {cout << " " << i << endl; Sleep(1000);}}
  15. );
  16.  
  17. return 0;
  18. }

This example will launch two functions in parallel if you have more than one core. The first function will print the numbers 0 to 100 and waits 100 milliseconds between two numbers. The second function will print the numbers 0 to 10 and will wait one second between two numbers. When you execute the above application on a system with more than one core, you will see that the numbers will interleave each other. Note that I didn't include any synchronization, so some numbers might appear on the same line. The parallel_invoke function can accept from 2 up to 10 functions to run in parallel. parallel_for internally is using parallel_invoke to split its work.

Profiling Parallel Code

Visual Studio 2010 CTP contains a new profiling option to help you in profiling the concurrency of your application. It allows you to check CPU utilization, thread blocking, and core execution. Explaining this profiler is outside the scope of this article. You can find some more information regarding it at http://msdn.microsoft.com/en-us/magazine/cc817396.aspx.



About the Author

Marc Gregoire

Marc graduated from the Catholic University Leuven, Belgium, with a degree in "Burgerlijk ingenieur in de computer wetenschappen" (equivalent to Master of Science in Engineering in Computer Science) in 2003. In 2004 he got the cum laude degree of Master In Artificial Intelligence at the same university. In 2005 he started working for a big software consultancy company. His main expertise is C/C++ and specifically Microsoft VC++ and the MFC framework. Next to C/C++, he also likes C# and uses PHP for creating webpages. Besides his main interest for Windows development, he also has experience in developing C++ programs running 24x7 on Linux platforms and in developing critical 2G,3G software running on Solaris for big telecom operators.

Downloads


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值