1.. _destroy_graphs_outside_main_thread:
2
3Destroying Graphs That Run Outside the Main Thread
4==================================================
5
6Make sure to enqueue a task to wait for and destroy graphs that run outside the main thread.
7
8You may not always want to block the main application thread by calling
9wait_for_all(). However, it is safest to call wait_for_all on a graph
10before destroying it. A common solution is to enqueue a task to build
11and wait for the graph to complete. For example, assume you really do
12not want to call a wait_for_all in the example from :ref:`always_use_wait_for_all`,
13Instead you can enqueue a task that creates the graph and waits for it:
14
15
16::
17
18
19   class background_task {
20   public:
21     void operator()() {
22       graph g;
23       function_node< int, int > f( g, 1, []( int i ) -> int {
24         return spin_for(i);
25       } );
26       f.try_put(1);
27       g.wait_for_all();
28     }
29   };
30
31
32   void no_wait_for_all_enqueue() {
33     task_arena a;
34     a.enqueue(background_task());
35     // do other things without waiting…
36   }
37
38
39In the code snippet above, the enqueued task executes at some point, but
40it's not clear when. If you need to use the results of the enqueued
41task, or even ensure that it completes before the program ends, you will
42need to use some mechanism to signal from the enqueued task that the
43graph is complete.
44
45