非同期通知

118) Postgres supports asynchronous notification via the LISTEN and NOTIFY commands. A backend registers its interest in a particular notification condition with the LISTEN command (and can stop listening with the UNLISTEN command). All backends listening on a particular condition will be notified asynchronously when a NOTIFY of that condition name is executed by any backend. No additional information is passed from the notifier to the listener. Thus, typically, any actual data that needs to be communicated is transferred through a database relation. Commonly the condition name is the same as the associated relation, but it is not necessary for there to be any associated relation.

Postgres は LISTEN と NOTIFY コマンドによる非同期通知機能をサポートしています. バックエンドは LISTEN コマンドを受け取ると, 特定の通知条件に関心を持ったことを登録します. (これを止めるには UNLISTEN コマンドを使います) 特定の条件を待っているすべてのバックエンドは, 同じ条件名の NOTIFY コマンドが任意のバックエンドによって実行された時点で 非同期的に通知を受けます. ただし通知の発行側から受信側へ渡される付加的な情報はありません. したがって,典型的には両者の間で受け渡す必要のある実際のデータは, データベースリレーションを通じて転送することになります. 一般的に,条件名は関連するリレーション名と同じものですが, 必ず関連するリレーションが必要とされるわけではありません.

119) libpq applications submit LISTEN and UNLISTEN commands as ordinary SQL queries. Subsequently, arrival of NOTIFY messages can be detected by calling PQnotifies().

libpq アプリケーションは, 通常の SQL による問い合わせと同じように LISTEN および UNLISTEN コマンドを発行することができます. 通知メッセージの到着は,続いて PQnotifies() を呼び出せば検出できます.

123) The second sample program gives an example of the use of asynchronous notification.

なお,二番目のサンプルプログラムが非同期通知を使用した例です.

124) PQnotifies() does not actually read backend data; it just returns messages previously absorbed by another libpq function. In prior releases of libpq, the only way to ensure timely receipt of NOTIFY messages was to constantly submit queries, even empty ones, and then check PQnotifies() after each PQexec(). While this still works, it is deprecated as a waste of processing power. A better way to check for NOTIFY messages when you have no useful queries to make is to call PQconsumeInput(), then check PQnotifies(). You can use select(2) to wait for backend data to arrive, thereby using no CPU power unless there is something to do. Note that this will work OK whether you use PQsendQuery/PQgetResult or plain old PQexec for queries. You should, however, remember to check PQnotifies() after each PQgetResult or PQexec to see if any notifications came in during the processing of the query.

PQnotify は実際にバックエンドのデータを読み出すわけではありません. これは単に,他の libpq 関数が吸収してしまっていた通知メッセージを返すだけです. 以前のリリースの libpq だと, 通知メッセージを適切な時点で確実に受け取るには, 空の問い合わせでもなんでも,とにかく一定時間ごとに問い合わせを送り, そして PQexec() を実行するたびに PQnotify() をチェックするしかありませんでした. 今でもこの方法は動作しますが,処理能力の無駄使いをすることになるので やめておいてください. 実行するべき問い合わせがないときに通知メッセージをチェックするよい方法は, まず PQconsumeInput() を呼び出し,それから PQnotifies() をチェックすることです. バックエンドからのデータの到着を select(2) で待つことができ, 不必要な動作で CPU パワーを消費してしまうことがありません. なお,これは問い合わせに PQsendQuery と PQgetResult を使ったときでも, またはおなじみの PQexec を使ったときでも動作します. しかし通知が問い合わせの処理中に届いていないかどうか, PQgetResult,あるいは PQexec の実行ごとに PQnotifies() を調べることを 忘れないようにしておくべきです.