C++期货并行处理

And*_*ton 13 c++ multithreading

我正在使用std::futures并行处理我的算法.我将信息拆分为互斥池,然后在自己的线程中对每个池执行相同的操作.代码如下所示:

class Processor
{
public:
    Processor(const std::string &strVal) : m_strVal(strVal)
    {
    }

    std::string GetVal() const {return m_strVal;}

    std::vector<std::string> Do()
    {
        // do some processing - this can throw an exception
    }

private:
    std::string m_strVal;
};

class ParallelAlgo
{
private:
    std::vector<std::string> m_vecMasterResults;

public:

    ProcessingFunction(const std::vector<std::string> &vecInfo)
    {
        // vecInfo holds mutually exclusive pools

        std::vector<std::future<std::vector<std::string> > > vecFutures(vecInfo.size());

        try
        {
            for (auto n = 0 ; n < vecInfo.size() ; n++)
            {
                vecFuture[n] = std::async(std::launch::async, &ParallelAlgo::WorkFunc, vecInfo[n].GetVal());
            }

            for (auto it = vecFutures.begin() ; it != vecFutures.end() ; ++it)
            {
                std::vector<std::string> RetVal = it->get();
                m_MasterResults.insert(m_MasterResults.begin(), RetVal.begin(), RetVal.end());
                vecFutures.erase(it);
            }
        }
        catch (exception &e)
        {
            for (auto it = vecFutures.begin() ; it != vecFuture.end() ; ++it)
            {
                // race condition?
                if (it->valid())
                {
                    it->wait_for(std::chrono::second(0));
                }
            }
        }
    }

    std::vector<std::string> ParallelAlgo::WorkFunc(const std::string &strVal)
    {
        Processor _Proccessor(strVal);
        return _Processor.Do();
    }
};
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在抛出异常时处理这种情况Processor:Do()?目前我使用a捕获异常future,然后等待每个future尚未完成的异常; 这很好 - 这些线程将简单地终止并且处理将不会完成.但是,我没有在catch块中引入竞争条件.一个future可以在valid()和之前完成的电话之间完成wait_for(),或者这不是一个问题,因为我没有呼吁get()这些不完整的未来?

use*_*083 3

调用valid仅检查是否存在相应的共享状态,对于已完成的线程来说,这仍然是正确的,直到您调用get它为止。

那里没有竞争条件。