いくつかの機能用に C API を設計しようとしていますが、公開された機能には時間がかかる可能性があるため、非同期にしたいと考えています。ブロッキング API の使用は、API のユーザーが多くの同時呼び出しを行う必要があるため、おそらくお勧めできません。
非同期操作が完了したことをユーザーに通知できるようにインターフェイスを設計する正しい方法は何ですか?
いくつかの異なるアプローチを考えることができますが、これに関するベスト プラクティスを認識しているとは言えません。同様の API を使用した経験のある人はいますか?
この例では、回答を含む int を返すことを意図しています。
コールバック関数:
typedef void (*callback_function)(int, void *);
/* Calls the callback function with the answer and cookie when done */
error_code DoSomething(callback_function, void *cookie);
ポーリング:
error_code DoSomething(void *cookie);
/* Blocks until any call has completed, then returns the answer and cookie */
error_code WaitForSomething(int *answer, void **cookie);
プラットフォーム固有のイベント キュー
/* Windows version, the api calls PostQueuedCompletionStatus when done */
error_code DoSomething( HANDLE hIoCompletionPort,
ULONG_PTR dwCompletionKey,
LPOVERLAPPED lpOverlapped );
通常、この API のユーザーはイベント駆動型であるため、以下のような設計はおそらく適切ではありません。
先物:
/* External dummy definition for a future */
struct Future_Impl {
int unused;
};
typedef Future_Impl *Future;
/* Initializes a future, so that it can be waited on later */
error_code DoSomething(Future *future);
/* Blocks until the result is available */
error_code WaitForSomething(Future future, int *answer);
プラットフォーム固有の「先物」/イベント:
/* Windows version, the api signals the event when done */
error_code DoSomething( HANDLE hEvent, int *answer );
/* Can be waited on using WaitForMultipleObjects,
but that has a limit on how many events that can be used */