我即将为某些功能设计一个 C api,我想让它异步,因为公开的功能可能需要一些时间。使用阻塞 api 可能不是一个好主意,因为 api 的用户需要同时进行许多调用。
设计界面的正确方法是什么,以便我可以通知用户异步操作已完成?
我可以想到几种不同的方法,但我不能说我知道这方面的最佳实践。有没有人有类似 API:s 的经验?
在此示例中,目的是返回一个包含答案的 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 */