Skip to content

Async++

Async++

There have been many proposals to extend the C++ model of futures. Most proposals involve the capability of continuations without polling. One of this proposals is N3428, inspired by the Microsoft PPL library. Async++ is a lightweight library that implements the concept.

1
2
3
4
5
FetchContent_Declare(asyncplusplus GIT_REPOSITORY https://github.com/Amanieu/asyncplusplus.git GIT_TAG v1.1)
FetchContent_MakeAvailable(asyncplusplus)
add_executable(async_pools async_pools.cpp)
target_link_libraries(async_pools PUBLIC Async++)
target_compile_features(async_pools PUBLIC cxx_std_17)

1
2
3
4
5
6
7
auto task1 = async::spawn(
    [] { std::cout << "Task 1 executes asynchronously" << '\n'; });

auto task2 = async::spawn([]() -> int {
    std::cout << "Task 2 executes in parallel with task 1" << '\n';
    return 42;
});

1
2
3
4
5
auto task3 = task2.then([](int value) -> int {
    std::cout << "Task 3 executes after task 2, which returned " << value
              << '\n';
    return value * 3;
});

1
2
3
4
5
6
auto task4 = async::when_all(task1, task3);
auto task5 =
    task4.then([](std::tuple<async::task<void>, async::task<int>> results) {
        std::cout << "Task 5 executes after tasks 1 and 3. Task 3 returned "
                  << std::get<1>(results).get() << '\n';
    });

1
2
task5.get();
std::cout << "Task 5 has completed" << '\n';

1
2
3
async::parallel_invoke(
    [] { std::cout << "This is executed in parallel..." << '\n'; },
    [] { std::cout << "with this" << '\n'; });

1
2
async::parallel_for(async::irange(0, 5), [](int x) { std::cout << x; });
std::cout << '\n';

1
2
3
int r = async::parallel_reduce({1, 2, 3, 4}, 0,
                               [](int x, int y) { return x + y; });
std::cout << "The sum of {1, 2, 3, 4} is " << r << '\n';

Share Snippets