]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp14/executors/async_2.cpp
6f40a902c8ada28e8e4aaca84bd22d7fcd32cc9d
[ceph.git] / ceph / src / boost / libs / asio / example / cpp14 / executors / async_2.cpp
1 #include <boost/asio/ts/executor.hpp>
2 #include <boost/asio/thread_pool.hpp>
3 #include <iostream>
4 #include <string>
5
6 using boost::asio::bind_executor;
7 using boost::asio::dispatch;
8 using boost::asio::get_associated_executor;
9 using boost::asio::make_work_guard;
10 using boost::asio::post;
11 using boost::asio::thread_pool;
12
13 // A function to asynchronously read a single line from an input stream.
14 template <class Handler>
15 void async_getline(std::istream& is, Handler handler)
16 {
17 // Create executor_work for the handler's associated executor.
18 auto work = make_work_guard(handler);
19
20 // Post a function object to do the work asynchronously.
21 post([&is, work, handler=std::move(handler)]() mutable
22 {
23 std::string line;
24 std::getline(is, line);
25
26 // Pass the result to the handler, via the associated executor.
27 dispatch(work.get_executor(),
28 [line=std::move(line), handler=std::move(handler)]() mutable
29 {
30 handler(std::move(line));
31 });
32 });
33 }
34
35 // A function to asynchronously read multiple lines from an input stream.
36 template <class Handler>
37 void async_getlines(std::istream& is, std::string init, Handler handler)
38 {
39 // Get the final handler's associated executor.
40 auto ex = get_associated_executor(handler);
41
42 // Use the associated executor for each operation in the composition.
43 async_getline(is,
44 bind_executor(ex,
45 [&is, lines=std::move(init), handler=std::move(handler)]
46 (std::string line) mutable
47 {
48 if (line.empty())
49 handler(lines);
50 else
51 async_getlines(is, lines + line + "\n", std::move(handler));
52 }));
53 }
54
55 int main()
56 {
57 thread_pool pool;
58
59 std::cout << "Enter text, terminating with a blank line:\n";
60
61 async_getlines(std::cin, "",
62 bind_executor(pool, [](std::string lines)
63 {
64 std::cout << "Lines:\n" << lines << "\n";
65 }));
66
67 pool.join();
68 }