在循环中多次发布未来和新线程

时间:2013-10-17 13:52:14

标签: c++ multithreading future

我正在编写一个程序,在多个线程中进行计算并使用c ++ future返回结果,这是我的代码的简化版本

int main()
{
    int length = 64;
    vector<std::future<float>> threads(length);
    vector<float> results(length);
    int blockLength = 8;
    int blockCount = length/blockLength;

    for(int j=0;j<blockCount;j++)
    {
        for(int i=0;i<blockLength;i++)
        {
            threads[i + j * blockLength] = std::async(func1,i*j);
        }

        for(int i=0;i<blockLength;i++)
        {
            results[i + j * blockLength] = threads[i].get();
        }
    }

func1的定义简化如下:

float func1(int input)
{
    //calculations...
    return result;
}

我希望上面的程序能够进行64次计算,一次8个线程,这样处理器和内存的使用率会同时提高。

该程序被认为它将一次发布blockLength个线程数,并等到获得计算结果,然后继续下一个循环。

程序将blockLength次发布blockCount个帖子,例如,8个帖子共8次。

但程序无效,EXC_BAD_ACCESS线程的第一个循环结束时总会有blockLength异常,此外,每个线程的计算时间不能保证,任何线程都可以运行很长一段时间或很快完成。

以下是截图: exception at the beginning of a new loop

如上所示,CPU使用率随着一些线程的完成而下降,但是一旦第二个循环开始就会抛出异常。

请指出我使用future时出了什么问题? 我们如何纠正它?

非常感谢!

0 个答案:

没有答案