我正准备为某些功能设计一个 C api,并且我想让它异步,因为公开的功能可能需要一些时间。使用阻塞 api 可能不是一个好主意,因为 api 的用户将需要同时进行许多调用。
如何设计界面才能通知用户异步操作已完成?
我可以想到几种不同的方法,但我不能说我知道这方面的最佳做法。有没有人有过类似 API:s 的经验?
在这个例子中,目的是返回一个包含答案的整数。
回调函数:
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 的用户通常是事件驱动的,因此像下面这样的设计可能不是一个好主意。
future :
/* 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);
平台特定的“ future ”/事件:
/* 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 */
最佳答案
我会选择回调函数作为基本构建 block 。我已经看到这个设计被使用了很多次并且很有效。 void 指针允许您传递一些上下文,而另一个回调参数通常是错误代码。您可以在此之上构建其他层,例如状态机、事件队列或在上下文中传递操作系统同步对象。
关于c - 异步c api设计的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799339/