I am executing n task using std::for_each and these tasks can be canceled. So for doing that I have a flag that is set to true if tasks to be canceled which in turn throws some exception in the task's code. And it works fine if I use normal std::for_each, but it aborts if I use any of std execution_policy. Is there a way to stop my code from aborting?
#include <execution>
#include <array>
#include <chrono>
#include <exception>
using namespace std::chrono_literals;
auto main(int argc, char* argv[]) -> int {
std::array<int, 5> x {1, 2, 3, 4, 5};
std::atomic<bool> toBeCancelled = true;
std::for_each(std::execution::par, std::begin(x), std::end(x), [&](const int& x) {
std::this_thread::sleep_for(2s);
if (toBeCancelled)
throw std::runtime_error("taskCancelled");
});
return 0;
}
The number of tasks can be 1000-10000. I usually don't use exceptions, instead I cover major code in "if condition". but here task count is so large, I thought running code outside of "if condition" is not worth it.