c - 异步c api设计的最佳实践

标签 c api-design

我正准备为某些功能设计一个 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/

相关文章:

c - 为什么 fscanf 使用 2 次 : while( ! feof(File))

c++ Windows - 如何从其路径获取进程PID

node.js - 休息 API : Should I associate the access token with a user in my database

xml - 开源/免费的通用 EPG/XMLTV 数据 API 或服务,或者如何制作?

对 DLL 和 WM_QUERYENDSESSION 中的 CTRL_SHUTDOWN_EVENT 处理感到困惑

c - GeoLiteCityv6.dat 里面有城市和地区数据吗?

Restful 设计,如何创建授权服务

haskell - 管道和非管道代码之间的并发注意事项

c++ - 基于 BGL 的新类中的自定义函数 addEdge 的返回值应该是多少?

c - 尽管禁用了缓冲,但 Printf 没有立即打印