1 | // |
2 | // wait_for_one.cpp |
3 | // ~~~~~~~~~~~~~~~~ |
4 | // |
5 | // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) |
6 | // |
7 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
8 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
9 | // |
10 | |
11 | #include <boost/asio.hpp> |
12 | #include <boost/asio/experimental/parallel_group.hpp> |
13 | #include <iostream> |
14 | |
15 | #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) |
16 | |
17 | int main() |
18 | { |
19 | boost::asio::io_context ctx; |
20 | |
21 | boost::asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); |
22 | boost::asio::steady_timer timer(ctx, std::chrono::seconds(5)); |
23 | |
24 | char data[1024]; |
25 | |
26 | boost::asio::experimental::make_parallel_group( |
27 | ops: [&](auto token) |
28 | { |
29 | return in.async_read_some(boost::asio::buffer(data), token); |
30 | }, |
31 | ops: [&](auto token) |
32 | { |
33 | return timer.async_wait(token); |
34 | } |
35 | ).async_wait( |
36 | cancellation_condition: boost::asio::experimental::wait_for_one(), |
37 | token: []( |
38 | std::array<std::size_t, 2> completion_order, |
39 | boost::system::error_code ec1, std::size_t n1, |
40 | boost::system::error_code ec2 |
41 | ) |
42 | { |
43 | switch (completion_order[0]) |
44 | { |
45 | case 0: |
46 | { |
47 | std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n" ; |
48 | } |
49 | break; |
50 | case 1: |
51 | { |
52 | std::cout << "timer finished: " << ec2 << "\n" ; |
53 | } |
54 | break; |
55 | } |
56 | } |
57 | ); |
58 | |
59 | ctx.run(); |
60 | } |
61 | |
62 | #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) |
63 | int main() {} |
64 | #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) |
65 | |