0

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

根据这个问题

在 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, OutputDim, InputDim));
        }
        for (auto& future : processingThread) {
            opMatArr.emplace_back(future.get());
        }
}

我在该行收到“读取访问冲突”的运行时异常opMatArr.emplace_back(future.get());

当我检查processingThread变量时,它将所有future值显示为待处理。那么,如果问题中的上述引用是正确的,我的代码不应该等到它获得所有future值吗?否则,此答案提供了以下解决方案,以等待您从中获得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;
}
4

0 回答 0