Using source_node

By default, an input_node is constructed in the inactive state:

template< typename Body > input_node( graph &g, Body body )

To activate an inactive input_node, you call the node's function activate:

    input_node< int > src( g, src_body(10) );
    // use it in calls to make_edge…
    src.activate();

All input_nodes are constructed in the inactive state and usually activated after the entire flow graph is constructed.

For example, you can use the code in Data Flow Graph. In that implementation, the input_node is constructed in the inactive state and activated after all other edges are made:

      make_edge( squarer, summer );
      make_edge( cuber, summer );
      input_node< int > src( g, src_body(10) );
      make_edge( src, squarer );
      make_edge( src, cuber );
      src.activate();
      g.wait_for_all();

In this example, if the input_node were toggled to the active state at the beginning, it might send a message to squarer immediately after the edge to squarer is connected. Later, when the edge to cuber is connected, cuber will receive all future messages, but may have already missed some.

Some graphs can be constructed safely with input_nodes active, allowing the overlap of construction and execution. If your graph is a directed acyclic graph (DAG), and each input_node has only one successor, you can construct your input_nodes in the active state if you construct the edges in reverse topological order; that is, make the edges at the largest depth in the tree first, and work back to the shallowest edges. For example, if src is a input_node and func1 and func2 are both function nodes, the following graph would not drop messages, even though src is constructed in the active state:

    const int limit = 10;
    int count = 0;
    graph g;
    input_node<int> src( g, [&]( int &v ) -> bool {
      if ( count < limit ) {
        ++count;
        v = count;
        return true;
      } else {
        return false;
      }
      } );
    src.activate();

    function_node<int,int> func1( g, 1, []( int i ) -> int {
      cout << i << "\n";
      return i;
    } );
    function_node<int,int> func2( g, 1, []( int i ) -> int {
      cout << i << "\n";
      return i;
    } );

    make_edge( func1, func2 );
    make_edge( src, func1 );

    g.wait_for_all();

The above code is safe because the edge from func1 to func2 is made before the edge from src to func1. If the edge from src to func1 were made first, func1 might generate a message before func2 is attached to it; that message would be dropped. Also, src has only a single successor. If src had more than one successor, the successor that is attached first might receive messages that do not reach the successors that are attached after it.

For more complete information about compiler optimizations, see our Optimization Notice.