1.. _cancel_a_graph: 2 3Cancel a Graph Explicitly 4========================= 5 6 7To cancel a graph execution without an exception, you can create the 8graph using an explicit task_group_context, and then call 9cancel_group_execution() on that object. This is done in the example 10below: 11 12 13:: 14 15 16 task_group_context t; 17 graph g(t); 18 19 20 function_node< int, int > f1( g, 1, []( int i ) { return i; } ); 21 22 23 function_node< int, int > f2( g, 1, 24 []( const int i ) -> int { 25 cout << "Begin " << i << "\n"; 26 spin_for(0.2); 27 cout << "End " << i << "\n"; 28 return i; 29 } ); 30 31 32 function_node< int, int > f3( g, 1, []( int i ) { return i; } ); 33 34 35 make_edge( f1, f2 ); 36 make_edge( f2, f3 ); 37 f1.try_put(1); 38 f1.try_put(2); 39 spin_for(0.1); 40 t.cancel_group_execution(); 41 g.wait_for_all(); 42 43 44When a graph execution is canceled, any node that has already started to 45execute will execute to completion, but any node that has not started to 46execute will not start. So in the example above, f2 will print both the 47Begin and End message for input 1, but will not receive the input 2. 48 49 50You can also get the task_group_context that a node belongs to from 51within the node body and use it to cancel the execution of the graph it 52belongs to: 53 54 55:: 56 57 58 graph g; 59 60 61 function_node< int, int > f1( g, 1, []( int i ) { return i; } ); 62 63 64 function_node< int, int > f2( g, 1, 65 []( const int i ) -> int { 66 cout << "Begin " << i << "\n"; 67 spin_for(0.2); 68 cout << "End " << i << "\n"; 69 task::self().group()->cancel_group_execution(); 70 return i; 71 } ); 72 73 74 function_node< int, int > f3( g, 1, []( int i ) { return i; } ); 75 76 77 make_edge( f1, f2 ); 78 make_edge( f2, f3 ); 79 f1.try_put(1); 80 f1.try_put(2); 81 g.wait_for_all(); 82 83 84You can get the task_group_context from a node's body even if the graph 85was not explicitly passed one at construction time. 86 87