how to exit a std::execution::par_unseq loop based on a condition

Viewed 183

I need to exit the loop, if one of my queue elements satisfies a condition. putting break results in a compile error. what is the best way to execute the loop parallel

//code

std::deque<element> my_elements;

std::for_each(std::execution::par_unseq, my_elements.begin(), my_elements.end(),
    [&](auto v) {

    if (v.attribute == something)
    {
        break;
    }
});
1 Answers

I'm pretty sure that won't work. Why? because break is a statically scoped operation; i.e, the destination for the break is determined at compile time. Putting it into a lambda (w the loop external to the lambda) makes it impossible for the compiler to see where to "break to".

Example w/o parallelism:

    vector<int> v {1,2,3,4,5,6,7,8,9};
    std::for_each(v.begin(), v.end(),
        [](int i) { cout << i << ' '; if (i == 5) break; });
    cout << endl;

gives me the following error:

so.cpp:10:45: error: 'break' statement not in loop or switch statement
     [](int i) { cout << i << ' '; if (i == 5) break; });

To answer your question; I don't think there's a good way to break out of for_each in a parallel algorithm. For the non-parallel case, you could throw an exception, but that won't work in the parallel case.

Related