如何在异步模型中使用回调结果

How to use callback results in asynchronous model C++

本文关键字:回调 结果 模型 异步      更新时间:2023-10-16

我有一个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"
}