4

我即将为某些功能设计一个 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 */
4

2 回答 2

2

我会选择回调函数作为基本构建块。我已经看到这种设计使用了很多次,而且很有效。void 指针允许您传递一些上下文,而另一个回调参数通常是错误代码。您可以在此之上构建其他层,例如状态机、事件队列或在上下文中传递操作系统同步对象。

于 2011-01-26T00:08:38.310 回答
0

我知道你要求一个特定的场景,但就设计 C 接口而言,我听到了关于这本书的非常积极的评论,并且通常听到它首先推荐给与你类似的问题:C 接口和实现:创建技术可重复使用的软件

于 2011-01-25T22:05:27.817 回答