の知識を c++20
時代にアップデート。
に動画と動画のサンプルコードが有る。
compiler を最新にする
ASIO_HAS_CO_AWAIT
が必要でこれが有効になるには新しいコンパイラが必要。
VC2019(20210818最新版いける)
C++20 coroutines in Visual Studio 2019 version 16.8.
16.7.3
だめ16.11.1
動いた。
LLVM-12(うまくいかず。追加のコマンドライン引数か)
LLVM-12 だと、
わからん。
コード
co_spawn で awaitable を起動する
coroutine は 戻り値の型が asio::awaitable<T>
である必要がある。この関数の中で co_await
, co_yield
, co_return
が使える。
coroutine は lambda でもよいので、下記のようにできる。
asio::use_future を使うことで返り値 std::future
になるので co_return
の値を得ることも可能。
結果に興味がないときは、asio::detached
でよい。
Completion Handler というコールバックなので、 promise に set_value する関数を自前で書いたりしてもよい様子。
asio::use_awaitable
で co_await
するのも可能。
返り値が std::tuple<asio::error_code, RESULT>
になるハンドラ。
client side
- timer
- connect
- send(ping)
- receive(pong)
server side
ループ(io_context)が隠蔽されていないのが良いですね。
asio api
io_context
c++23
の Networking TS
に向けた変更?
- Networking TS の Boost.Asio からの変更点 - その 1: Associated allocator
- Networking TS の Boost.Asio からの変更点 - その 3: Executor
io_service は Executor と ExecutionContext という概念に分割されたことで, io_context に名前が変わりました
Boost 1.66
単純に io_service を io_context に追きかえるだけで動いた。
endpoint
ipaddress + port
tcp connect
socket
basic
c++11 future
std::future に対して continue_with
する手段を用意しないと、これ単体では使いづらい
c++20 coroutine
有望
tcp listen
raed_async
write_async
coroutine 詳細
asio の coroutine を学んでいたらできないことが出てきた。
自前の Awaiter が必要?
co_await std::future
できるぽいが, asio
と混ぜてうまくいくのだろうか。
c++20 coroutine
- https://cpprefjp.github.io/lang/cpp20/coroutines.html
- https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html
- C++ でコルーチン (async/await 準備編)
- C++ で async/await をする
内部で co_await
, co_yield
, co_return
の何れかを使う関数は coroutine になる。
返り値の型から promise_type を得られるようにする必要がある。
初期化は promise_type::get_return_object
から始まるぽい。
generator の例
Asio の実装
asio::awaitable
asio::awaitable<T>
が CoroutineTrait の実装。
include/asio/awaitable.hpp
promise_type
include/asio/impl/awaitable.hpp
// promise_type