YACLib
C++ library for concurrent tasks execution
Loading...
Searching...
No Matches
when_any.cpp
Go to the documentation of this file.
1/**
2 * \example when_any.cpp
3 * Simple WhenAny examples
4 */
10
11#include <chrono>
12#include <iostream>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17#include <gtest/gtest.h>
18
19namespace test {
20namespace {
21
22using namespace std::chrono_literals;
23
24// Any combinator:
25// std::vector<Future<T>> -> Future<T>
26
27TEST(Example, WhenAny) {
29
30 std::vector<yaclib::FutureOn<int>> futs;
31
32 // Run sync computations in parallel
33
34 for (int i = 0; i < 5; ++i) {
35 futs.push_back(yaclib::Run(tp, [i]() -> int {
36 return i;
37 }));
38 }
39
40 // Parallel composition
41 // Any combinator: std::vector<Future<T>> -> Future<T>
42 // Non-blocking!
43 yaclib::Future<int> any = WhenAny(futs.begin(), futs.size());
44
45 // First value
46 std::cout << "Any value: " << std::move(any).Get().Ok() << std::endl;
47
48 tp.Stop();
49 tp.Wait();
50}
51
52TEST(Example, WhenAnyShared) {
54
55 std::vector<yaclib::SharedFutureOn<int>> futs;
56
57 // Run sync computations in parallel
58
59 for (int i = 0; i < 5; ++i) {
60 futs.push_back(yaclib::RunShared(tp, [i]() -> int {
61 return i;
62 }));
63 }
64
65 // Parallel composition
66 // Any combinator: std::vector<Future<T>> -> Future<T>
67 // Non-blocking!
68 yaclib::Future<int> any = WhenAny(futs.begin(), futs.size());
69
70 // First value
71 std::cout << "Any value: " << std::move(any).Get().Ok() << std::endl;
72
73 tp.Stop();
74 tp.Wait();
75}
76
77} // namespace
78} // namespace test
TODO(kononovk) Doxygen docs.
Provides a mechanism to access the result of async operations.
Definition future.hpp:211
auto Run(Func &&f)
Execute Callable func on Inline executor.
Definition run.hpp:57
auto RunShared(Func &&f)
Definition run.hpp:62
YACLIB_INLINE auto WhenAny(Futures... futures)
Definition when_any.hpp:13
TEST(Example, HelloWorld)
Definition simple.cpp:27