为什么在从 std::future 访问值时会抛出“读取访问冲突”异常?

问题描述

编辑:我的问题与建议的问题不同,因为我无法轮询 100 个 future.get() 并等待在 main() 线程中执行剩余的程序。我希望线程在线程执行完毕后返回值,然后调用函数应该运行。

根据this question

在C++中future等待结果并暂停下一行代码

我有以下代码,我在其中创建了大约 100 个异步线程,然后检索返回变量;

void BEVTest::runTests()
{   
    CameraToBEV cbevObj(RoiBBox,OutputDim,InputDim);
    // for multithreading
    std::vector<std::future<cv::Mat>> processingThread;
    std::vector<cv::Mat> opMatArr;
    
        for (int i = 0; i < jsonObjects.size(); i++) {
                processingThread.emplace_back(std::async(std::launch::async,&CameraToBEV::process,&cbevObj,std::ref(jsonObjects[i]),RoiBBox,InputDim));
        }
        for (auto& future : processingThread) {
            opMatArr.emplace_back(future.get());
        }
}

我在行 opMatArr.emplace_back(future.get());

处收到“读取访问冲突”的运行时异常

当我检查 processingThread 变量时,它显示所有 future 值都处于待处理状态。因此,如果问题的上述引用是正确的,我的代码不应该等到它获得所有 future 值吗?否则 this answer 提供以下解决方案以等待您从 future

获得 future.get()
auto f = std::async(std::launch::async,my_func)
    .then([] (auto fut) {
        auto result = fut.get();
        /* Do stuff when result is ready. */
    });

但这对我来说是不可能的,因为那样我将不得不轮询所有 100 个 future.get() 并且它会产生开销,这将违背创建线程的目的。

我有两个问题; 1> 为什么会出现运行时异常? 2> 如何等到所有 100 个 future.get() 返回值?

编辑:我提供了我的流程功能

cv::Mat CameraToBEV::process(json& jsonObject,std::vector<Point2f> roibBox,Point2f opDim,Point2f ipDim)
{   // Parameters
    img_width = imgWidth = opDim.x;
    img_height = imgHeight = opDim.y;
    for (int i=0; i<roibBox.size(); i++)
    {
        roiPoints[i] = roibBox[i];
    }

    // From Centroids class
    jsonObj = jsonObject; 
    initializeCentroidMatrix();
    getBBoxes();
    transformCoordinates();

    // From Plotter class
    cv::Mat resultImg = plotLocation(finalCentroids,violationArr,ipDim,opDim);
    return resultImg;
}

解决方法

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

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

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