地方エンジニアの学習日記

興味ある技術の雑なメモだったりを書いてくブログ。たまに日記とガジェット紹介。

【Linux】非同期IOブロッキングとかノンブロッキングの話

ブロッキングとかノンブロッキングとかの復讐してたら突如上の疑問が沸いたので調べてみた。

非同期ブロッキング/非同期ノンブロッキングの違い

良くある教科書的な違いだとそれぞれ以下のような図になる。

非同期ブロッキングではシステムコールカーネルコンテキストスイッチして監視したいfdを登録してselect(2)でブロックする。読み込み可能状態のFDがあったらユーザプロセス へ通知してユーザプロセスはread(2)を行ってカーネルスペースからデータを持ってくる仕組み。このメリットとしてはselectで確認する際に複数のfdを同時に監視できるという点。同期ノンブロッキングとの違いは主にこれ

f:id:ryuichi1208:20210109104228p:plain

非同期ノンブロッキングの場合はユーザプロセスはカーネルへIOを要求して終わる。監視もCBを登録しておけばカーネルがよしなにやってくれて通知が来た時点でデータもユーザスペースに存在するという仕組み。

f:id:ryuichi1208:20210109104635p:plain

何が疑問か

非同期ブロッキングのどの辺が非同期なんだろうという疑問。監視もIOもブロックしてるしで非同期とは?という疑問でした。結論としてはselectやepoll単体の利用で非同期を実現するのではなくそれ+で非同期ブロッキングを実現するらしい。

実装例としてはnode.jsが使っているlibuv/libuvlibeioなんかがある。これらはそれぞれ独自にIO用のスレッドプールなりプロセスを生成しておきIOはそちらで行い通知時にはユーザスペースにデータが存在するような仕組みを取っている(ここはちょっと曖昧でファイルIOは専用スレッドを使っているが他は不明)

libuvとは(特にイベントループについて) - kkty’s blog

epollやらselectを使っただけでは同期ブロッキングになってしまうのでsocketの作成時のオプションも必要。

Nginxでは

blog.matsumoto-r.jp

Nginxではキャッシュ周りで非同期I/Oを使っているらしい。コンパイルオプションの指定は必須だがlibaioとか入っている環境であればすんなりと使用することは可能そう。

ちなみにDockerで公式のnginxを使えばさっと試せたりします。aioディレクティブとか触ったことないので試してみよう。

root@57d9a1069671:/# nginx -V | grep aio
nginx version: nginx/1.19.6
built by gcc 8.3.0 (Debian 8.3.0-6)
built with OpenSSL 1.1.1d  10 Sep 2019
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/nginx-1.19.6/debian/debuild-base/nginx-1.19.6=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'