1.. _always_use_wait_for_all: 2 3Always Use wait_for_all() 4========================= 5 6 7One of the most common mistakes made in flow graph programming is to 8forget to call wait_for_all. The function graph::wait_for_all blocks 9until all tasks spawned by the graph are complete. This is not only 10useful when you want to wait until the computation is done, but it is 11necessary to call wait_for_all before destroying the graph, or any of 12its nodes. For example, the following function will lead to a program 13failure: 14 15 16:: 17 18 19 void no_wait_for_all() { 20 graph g; 21 function_node< int, int > f( g, 1, []( int i ) -> int { 22 return spin_for(i); 23 } ); 24 f.try_put(1); 25 26 27 // program will fail when f and g are destroyed at the 28 // end of the scope, since the body of f is not complete 29 } 30 31 32In the function above, the graph g and its node f are destroyed at the 33end of the function's scope. However, the task spawned to execute f's 34body is still in flight. When the task completes, it will look for any 35successors connected to its node, but by then both the graph and the 36node have been deleted out from underneath it. Placing a 37g.wait_for_all() at the end of the function prevents the premature 38destruction of the graph and node. 39 40 41If you use a flow graph and see mysterious behavior, check first to see 42that you have called wait_for_all. 43 44