What is the most efficient way to exit parallel_for? To exit the standard loop, we do the following:
for(int i = 0; i < 100; i+) { bool bValue = DoSomething(); //Break if bValue is true if(bValue) break; }
I did some research and I found some information on Cancel in PPL and I am considering 3 options
-Task Group
// To enable cancelation, call parallel_for in a task group. structured_task_group tg; task_group_status status = tg.run_and_wait([&] { parallel_for(0, 100, [&](int i) { bool bValue = DoSomething(); if (bValue) { tg.cancel(); } }); });
-Remove exception
try { parallel_for(0, 100, [&](int i) { bool bValue = DoSomething(); if (bValue) throw i; }); } catch (int n) { wcout << L"Caught " << n << endl; }
-Use the boolean
// Create a Boolean flag to coordinate cancelation. bool bCanceled = false; parallel_for(0, 100, [&](int i) { // Perform work if the task is not canceled. if (!bCanceled) { bool bValue = DoSomething(); if (bValue) bCanceled = true; } });
source share