1 #include <boost/asio/associated_executor.hpp>
2 #include <boost/asio/bind_executor.hpp>
3 #include <boost/asio/execution.hpp>
4 #include <boost/asio/static_thread_pool.hpp>
5 #include <iostream>
6 #include <string>
7
8 using boost::asio::bind_executor;
9 using boost::asio::get_associated_executor;
10 using boost::asio::static_thread_pool;
11 namespace execution = boost::asio::execution;
12
13 // A function to asynchronously read a single line from an input stream.
14 template <class IoExecutor, class Handler>
async_getline(IoExecutor io_ex,std::istream & is,Handler handler)15 void async_getline(IoExecutor io_ex, std::istream& is, Handler handler)
16 {
17 // Track work for the handler's associated executor.
18 auto work_ex = boost::asio::prefer(
19 get_associated_executor(handler, io_ex),
20 execution::outstanding_work.tracked);
21
22 // Post a function object to do the work asynchronously.
23 execution::execute(
24 boost::asio::require(io_ex, execution::blocking.never),
25 [&is, work_ex, handler=std::move(handler)]() mutable
26 {
27 std::string line;
28 std::getline(is, line);
29
30 // Pass the result to the handler, via the associated executor.
31 execution::execute(
32 boost::asio::prefer(work_ex, execution::blocking.possibly),
33 [line=std::move(line), handler=std::move(handler)]() mutable
34 {
35 handler(std::move(line));
36 });
37 });
38 }
39
main()40 int main()
41 {
42 static_thread_pool io_pool(1);
43 static_thread_pool completion_pool(1);
44
45 std::cout << "Enter a line: ";
46
47 async_getline(io_pool.executor(), std::cin,
48 bind_executor(completion_pool.executor(),
49 [](std::string line)
50 {
51 std::cout << "Line: " << line << "\n";
52 }));
53
54 io_pool.wait();
55 completion_pool.wait();
56 }
57