带有 std::async 的递归函数被某些大小的 std::vector 卡住

问题描述

我重写了获得所有向量组合的函数。我尝试异步运行它,当向量大小为 5 - getAllCombinationOfVector({ 1,2,3,4,5}) 时它工作正常。当向量大小为 6 时,它卡住了。当输入为 6 时,代码永远不会到达任何函数的末尾。

#include <thread>
#include <future>
#include <iostream>
#include <chrono>

std::vector<std::vector<int>> getAllCombinationOfVector(const std::vector<int> vec)
{
    return internalGetAllCombinationOfVector(vec,std::vector<int>());
}

std::vector<std::vector<int>> internalGetAllCombinationOfVector(const std::vector<int> remainIds,const std::vector<int> firstPart)
{
    std::vector<std::vector<int>> options;
    std::vector<int> newPart = firstPart;
    if (remainIds.size() == 1)
    {
        newPart.push_back(remainIds[0]);
        return std::vector<std::vector<int>>{newPart};
    }   
    std::vector<std::future<std::vector<std::vector<int>>>> tasks;
    for (auto itr=remainIds.begin();itr!=remainIds.end();itr++)
    {
        newPart = firstPart;
        newPart.push_back(*itr);
        

        std::vector<int> remainIdWithoutUsedId = std::vector<int>(remainIds.begin(),itr);
        remainIdWithoutUsedId.insert(remainIdWithoutUsedId.end(),itr + 1,remainIds.end());
        
        
        tasks.push_back(std::async(std::launch::async,internalGetAllCombinationOfVector,remainIdWithoutUsedId,newPart));
    }
    for (auto& task : tasks)
    {
        auto someOptions = task.get();
        options.insert(options.end(),someOptions.begin(),someOptions.end());
    }
    return options;

}

函数同步运行时它工作。 可能是什么问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)