forked from taskflow/taskflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.cpp
More file actions
57 lines (43 loc) · 1.52 KB
/
async.cpp
File metadata and controls
57 lines (43 loc) · 1.52 KB
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
// The program demonstrates how to create asynchronous task
// from an executor and a subflow.
#include <taskflow/taskflow.hpp>
int main() {
tf::Executor executor;
// create asynchronous tasks from the executor
// (using executor as a thread pool)
tf::Future<std::optional<int>> future1 = executor.async([](){
std::cout << "async task 1 returns 1\n";
return 1;
});
executor.silent_async([](){ // silent async task doesn't return
std::cout << "async task 2 does not return (silent)\n";
});
// create asynchronous tasks with names (for profiling)
executor.named_async("async_task", [](){
std::cout << "named async task returns 1\n";
return 1;
});
executor.named_silent_async("silent_async_task", [](){
std::cout << "named silent async task does not return\n";
});
executor.wait_for_all(); // wait for the two async tasks to finish
// create asynchronous tasks from a subflow
// all asynchronous tasks are guaranteed to finish when the subflow joins
tf::Taskflow taskflow;
std::atomic<int> counter {0};
taskflow.emplace([&](tf::Subflow& sf){
for(int i=0; i<100; i++) {
sf.silent_async([&](){ counter.fetch_add(1, std::memory_order_relaxed); });
}
sf.join();
// when subflow joins, all spawned tasks from the subflow will finish
if(counter == 100) {
std::cout << "async tasks spawned from the subflow all finish\n";
}
else {
throw std::runtime_error("this should not happen");
}
});
executor.run(taskflow).wait();
return 0;
}