我有一个关于“ppl.h” header 的 Concurrency::parallel_for 算法的问题。此示例来自 Ivor Horton 的书 - “Beginning Visual C++ 2010”。
完整 .cpp 文件的链接: http://media.wiley.com/product_ancillary/83/04705008/DOWNLOAD/500880ch13.zip “Ch13/Ex13_03/Ex13_03.cpp”
在这个特定示例中,他展示了如何使用并行计算构建 Mandelbrot 集。
处理它的函数是:
void DrawSetParallelFor(HWND hWnd)
{
// setting interface here
HDC hdc(GetDC(hWnd));
RECT rect;
GetClientRect(hWnd, & rect);
// getting width and height of our window
int imageHeight(rect.bottom);
int imageWidth(rect.right);
// defining variables and constants
const double realMin(-2.1); // Minimum real value
double imaginaryMin(-1.3); // Minimum imaginary value
double imaginaryMax(+1.3); // Maximum imaginary value
double realMax(realMin+(imaginaryMax-imaginaryMin)*imageWidth/imageHeight);
double realScale((realMax-realMin)/(imageWidth-1));
double imaginaryScale((imaginaryMax-imaginaryMin)/(imageHeight-1));
// defining critical section
Concurrency::critical_section cs; // Mutex for BitBlt() operation
// starting parallel loop
Concurrency::parallel_for(0, imageHeight, [&](int y)
{
// locking code
cs.lock();
HDC memDC = CreateCompatibleDC(hdc);
HBITMAP bmp = CreateCompatibleBitmap(hdc, imageWidth, 1);
cs.unlock();
HGDIOBJ oldBmp = SelectObject(memDC, bmp);
double cReal(0.0), cImaginary(0.0);
double zReal(0.0), zImaginary(0.0);
zImaginary = cImaginary = imaginaryMax - y*imaginaryScale;
// filling horizontal rows with colored pixels
for(int x = 0; x < imageWidth; ++x)
{
zReal = cReal = realMin + x*realScale;
SetPixel(memDC, x, 0, Color(IteratePoint(zReal, zImaginary, cReal, cImaginary)));
}
// locking again
cs.lock();
BitBlt(hdc, 0, y, imageWidth, 1, memDC, 0, 0, SRCCOPY);
cs.unlock();
// deleting objects
SelectObject(memDC, oldBmp);
DeleteObject(bmp);
DeleteDC(memDC);
});
ReleaseDC(hWnd, hdc);
}
基本上,此函数呈现 Mandelbrot 集,该集在 IteratePoint
函数中计算。
水平像素行以随机顺序呈现。我的问题是 - Concurrency::parallel_for
算法究竟是如何决定窗口的哪个区域(即一组“y”水平像素行)由哪个内核渲染的。
附注工作示例在这里:http://hotfile.com/dl/137661392/d63280a/MANDELBROT.rar.html
感谢您的宝贵时间!
最佳答案
从表面上看,parallel_for 对介于 0 和 imageHeight 之间的每个值调用一次 lambda 函数。有效地:
Concurrency::parallel_for(0, imageHeight, [&](int y) {
等同于:
for(int y=0; y<imageHeight; ++y) {
因此,lambda 函数会针对图像中的每个 y 调用一次,可能会在多个工作线程之间拆分调用以允许它们并行运行。
因为 parallel_for 是一个库函数,所以您真的不应该担心它在内部是如何工作的。只需接受它为每个 y 调用一次 lamda。严格来说,没有定义的顺序,因为多个调用可能同时发生(例如,在不同的处理器内核上)。
关于c++ - 多核编程/Mandelbrot Set/c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535404/