What is the most efficient way to undo parallel_for

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; } }); 
+4
source share
2 answers

The structured_task_group option is the only one that would really be reasonable. # 3 is just massively unsafe, and # 2 is just a terrible abuse of exceptions.

+2
source

Starting with Visual Studio 2012, there is a run_with_cancellation_token function that will execute lambda along with cancellation_token . Inside lambda

Reference: run_with_cancellation_token Function

Sample code can be found on MSDN at: How to use undo to interrupt from a parallel loop

I cannot talk about the "effectiveness" of this approach, since I suspect that the C ++ exception is related to its implementation. However, this code may be simpler than other approaches and allows you to use most PPL constructs without limiting structured_task_group .

+1
source

Source: https://habr.com/ru/post/1433442/


All Articles