如何在异步模型中使用回调结果
How to use callback results in asynchronous model C++
我有一个c++ API,它有一个特定的定义函数和相关的回调。所有这些函数本质上都是异步的。
现在,使用这个API,我想构造一个异步系统来发送多个请求向服务器收集不同的数据项,然后使用
例如:
void functionA()
{
requestDataForA(); //asynchronous request to the server
//async wait for the callback
processDataForA();
}
void functionB()
{
requestDataForB(); //asynchronous request to the server
//async wait for the callback
processDataForB();
}
void functionC()
{
requestDataForC(); //asynchronous request to the server
//async wait for the callback
processDataForC();
}
现在我的问题是,当回调给出数据项时,如何将其用于后续处理。在callback中不能这样做,因为callback不知道谁会使用这些数据。
谢谢
Shiv
您隐式地拥有这些信息,您只需要跟踪它。假设对象A
调用functionA
,您应该让A
实现一个特定的接口,该接口接受与调用requestA
的响应相关的数据。假设这个响应是DataA
,那么接口将是
class InterfaceADataHandler
{
public:
virtual void handle(DataA const&) = 0; // this is the method that will process the data..
};
class A : public InterfaceADataHandler
{
public:
void handle(DataA const&) {} // do something with data
// Now I want to be called back
void foo()
{
functionA(this); // call function A with this instance
}
};
void functionA(InterfaceADataHandler* pHandler)
{
// store this handler against request (say some id)
request..();
// wait for callback
// when you have callback, lookup the handler that requested the data, and call that handler
}
在大多数API中,开发人员将提供回调,该回调将由API使用已检索到的数据调用。然后,您可以存储数据并在以后使用它,或者在回调中使用它(假设您不会花费很长时间来处理并承诺不阻塞I/O)。
模型看起来更像:
void functionA()
{
requestDataForA(processDataForA); //asynchronous request to the server
}
void processDataForA(void *someData)
{
// process "someData"
}
相关文章:
- 架构决策:返回std::future还是提供回调
- 正在为Xtensa simcall函数编写回调函数
- 如何在C++中使用非静态成员函数作为回调函数
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 用于在回调中调用解析器的设计模式
- 如何使用C++对象的成员函数作为 C 样式回调?
- Java从C++回调到C++回调
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 从不同的 cpp 调用回调函数会导致bad_function_call
- pcap_handler回调仅在使用 NPCAP v0.9991 时包含空数据包
- 不带轮询的 SDL2 事件回调
- C++存储带有可变参数的回调
- 如何使用 Node-addon-API 实现 node-nan 回调
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 访问类C++ C 样式回调
- C++ 线程端回调并返回结果
- 接受任意数量的回调并存储结果的 C++ 类方法
- 脚本回调参数和结果的自动编组
- 如何在异步模型中使用回调结果