File: condition_dsl.cpp

package info (click to toggle)
taskflow 3.9.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 45,948 kB
  • sloc: cpp: 39,058; xml: 35,572; python: 12,935; javascript: 1,732; makefile: 59; sh: 16
file content (79 lines) | stat: -rw-r--r-- 1,811 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 2020/08/28 - Created by netcan: https://github.com/netcan
// Task DSL demo
// The example creates the following cyclic graph:
//
//       A
//       |
//       v
//       B<---|
//       |    |
//       v    |
//       C----|
//       |
//       v
//       D
//
// - A is a task that initializes a counter to zero
// - B is a task that increments the counter
// - C is a condition task that loops around B until the counter
//   reaches a breaking number
// - D is a task that wraps up the result
#include <taskflow/taskflow.hpp>
#include <taskflow/dsl.hpp>

int main() {
  tf::Executor executor;
  tf::Taskflow taskflow("Conditional Tasking Demo");

  int counter; // owner

  // use context to pass args
  // context must copyable
  struct Context {
    int &rcounter; // use counter(borrow)
  } context{counter};

  make_task((A, Context), {
    std::cout << "initializes the counter to zero\n";
    rcounter = 0;
  });
  make_task((B, Context), {
    std::cout << "loops to increment the counter\n";
    rcounter++;
  });
  make_task((C, Context), {
    std::cout << "counter is " << rcounter << " -> ";
    if (rcounter != 5) {
      std::cout << "loops again (goes to B)\n";
      return 0;
    }
    std::cout << "breaks the loop (goes to D)\n";
    return 1;
  });
  make_task((D, Context), {
    std::cout << "done with counter equal to " << rcounter << '\n';
  });

  auto tasks = build_taskflow(
    task(A)
      -> task(B)
      -> task(C),
    task(C)
      -> fork_tasks(B, D)
  )(taskflow, context);

  tasks.get_task<A>().name("A");
  tasks.get_task<B>().name("B");
  tasks.get_task<C>().name("C");
  tasks.get_task<D>().name("D");

  // visualizes the taskflow
  taskflow.dump(std::cout);

  // executes the taskflow
  executor.run(taskflow).wait();

  assert(counter == 5);

  return 0;
}