从 actor 调用返回值

Returning value from actor call

在 C++ Actor 框架中,我有一个 actor(假设 A)调用另一个 actor(假设 B),然后必须在 A 的逻辑中使用 B 的值。

为了更具体,代码如下:

behavior B(event_based_actor* self) {
return {
    [=](const string& what) -> string {
        return what;
    }
};

behavior A(event_based_actor* self) {
return {
    [=](const string& what, const actor& buddy) -> string {
            self->request(buddy, std::chrono::seconds(10), what)
        .then(
            [=](string & data) {
                aout(self) << data << endl;
            }
          what = data // here I have to use data and thats the issue
           );
        return what;
    }
};

从代码中可以看出,我必须使用数据变量,它是 lambda 之外的参与者 B 的结果,因为我是新手,所以任何帮助都将不胜感激。

并且 actor B 是从另一个阻塞 actor 调用的。

这是行不通的。 Event-based actors 是非阻塞的。语句 request(x).then(f)x 发送给另一个参与者,然后存储 f 以处理结果。换句话说,request(...).then(...) 总是 return 立即执行,而 f 在稍后的某个时间点执行。因此设置 what = data 没有任何效果,您将始终 return 原来的 what.

您要找的是响应承诺。它们允许您延迟响应。你的情况:

behavior A(event_based_actor* self) {
  return {
    [=](const string& what, const actor& buddy) -> result<string> {
      auto rp = self->make_response_promise();
      self->request(buddy, std::chrono::seconds(10), what)
      .then(
        [=](string& data) mutable {
          aout(self) << data << endl;
          rp.deliver(std::move(data));
        }
      );
      return rp;
    }
  };
}

您可以在 CAF 中包含的 manual and there's also a full example 中阅读更多关于承诺的信息。