在parallel_for循环中为每个线程分配内存

时间:2012-02-11 15:39:50

标签: c++ concurrency malloc parallel-processing parallel-for

我最初有一个单线程循环,它迭代图像的所有像素,并可以对数据进行各种操作。

我使用的库指示从图像中检索像素必须一次完成一行。为此,我malloc一个可以容纳一行像素的内存块(BMM_Color_fl是一个包含一个像素的RGBA数据作为四个浮点值的结构,GetLinearPixels()复制一行像素从位图到BMM_Color_fl数组。)

BMM_Color_fl* line = (BMM_Color_fl*)malloc(width * sizeof(BMM_Color_fl));
for (int y = 0; y < height, y++)
{   
    bmp->GetLinearPixels(0, y, width, line); //Copy data of row Y from bitmap into line.
    BMM_Color_fl* pixel = line; //Get first pixel of line.
    for (int x = 0; x < width; x++, pixel++) // For each pixel in the row...
    {
        //Do stuff with a pixel.
    }
}
free(line);

到目前为止一切顺利!

为了减少这个循环的执行时间,我使用parallel_for编写了一个并发版本,如下所示:

parallel_for(0, height, [&](int y)
{   
    BMM_Color_fl* line = (BMM_Color_fl*)malloc(width * sizeof(BMM_Color_fl));
    bmp->GetLinearPixels(0, y, width, line);
    BMM_Color_fl* pixel = line;
    for (int x = 0; x < width; x++, pixel++)
    {
        //Do stuff with a pixel.
    }
    free(line);
});

虽然多线程循环已经比原始循环快,但我意识到所有线程都不可能使用相同的内存块,所以目前我在每次循环迭代时分配和释放内存,这显然是浪费,因为它会永远不会比循环迭代更多的线程。

我的问题是,我是否以及如何让每个帖子malloc只有一个行缓冲区并重复使用它(理想情况下,最后将其释放)?

  • 作为免责声明,我必须说明我是新手C ++用户。

建议解决方案的实施:

Concurrency::combinable<std::vector<BMM_Color_fl>> line;

parallel_for(0, height, [&] (int y)
{
    std::vector<BMM_Color_fl> lineL = line.local();
    if (lineL.capacity() < width) lineL.reserve(width);

    bmp->GetLinearPixels(0, y, width, &lineL[0]);

    for (int x = 0; x < width; x++)
    {
         BMM_Color_fl* pixel = &lineL[x];
         //Do stuff with a pixel.
    }       
});

根据建议,我将malloc设为罐头,并将其替换为vector + reserve

2 个答案:

答案 0 :(得分:0)

不是让每个线程调用parallel_for()而是让它们调用另一个分配内存的函数,调用parallel_for(),然后释放内存。

答案 1 :(得分:0)

您可以使用Concurrency::combinable类来实现此目的。 我懒得发布代码,但我确信这是可能的。