dimanche 30 juillet 2017

Editing array with std::async

The idea was to perform operations on each element of array in parallel. I come up with the following:

struct dataContainer
{
    int value;
    bool flag;
    dataContainer()
        : value(1)
        , flag(true)
    {}
};


int main()
{
    std::vector<dataContainer> arrData;
    arrData.resize(10);

    {
        std::vector<std::future<void> > results;
        std::for_each(arrData.begin(), arrData.end(), [&results](dataContainer& tData) {

            results.emplace_back(std::async(std::launch::async, [](dataContainer& ttData) {
                ttData.value++;
                ttData.flag = false;
            }, tData));
        });
    }

    return 0;
}

However, lambda called by std::async doesn't perform operations on elements of arrData. Actually, I don't understand what is happening. It appears that operations are performed on local copy of dataContainer.

So the question is what is happening, and how can I perform operations on array elements in this manner?

Aucun commentaire:

Enregistrer un commentaire