我即将为某些功能设计一个 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);
Run Code Online (Sandbox Code Playgroud)
轮询:
error_code DoSomething(void *cookie);
/* Blocks until any call has completed, then returns the answer and cookie */
error_code WaitForSomething(int *answer, void **cookie);
Run Code Online (Sandbox Code Playgroud)
平台特定事件队列
/* Windows version, the api calls PostQueuedCompletionStatus when done */
error_code DoSomething( HANDLE hIoCompletionPort,
ULONG_PTR dwCompletionKey,
LPOVERLAPPED lpOverlapped );
Run Code Online (Sandbox Code Playgroud)
该 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);
Run Code Online (Sandbox Code Playgroud)
平台特定的“期货”/事件:
/* 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 */
Run Code Online (Sandbox Code Playgroud)
我知道您已经要求了一个特定的场景,但就设计 C 接口而言,我听到了关于这本书的非常积极的评论,并且通常会听到首先推荐它来解决与您类似的问题:C 接口和实现:创建技术可重复使用的软件