我正试图将一些作品从一个类型的演员交给另一个演员。 CAF用户手册表明可以使用forward_to
方法完成此操作。该方法看起来只适用于明确属于event_based_actor
类型的actor。但是,forward_to
似乎是forward_current_message
方法的一个瘦包装器,该方法是为local_actor
类型的所有actor定义的。因此,我认为可以直接拨打forward_current_message
吗?
此外,为了使消息转发与类型化actor一起工作,我仍然必须从中间actor返回响应。那个演员的反应似乎被忽略了,这很好,但我做错了吗?或者是否真的有必要支付构建不会被使用的响应的(通常是最小的)成本?
这是一些工作示例代码,演示了我尝试使用类型化actor进行消息转发:
#include <iostream>
#include "caf/all.hpp"
using namespace caf;
using namespace std;
using a_type = typed_actor<replies_to<int>::with<bool>>;
using b_type = typed_actor<replies_to<int>::with<bool>>;
actor worker()
{
return spawn(
[](event_based_actor *self) -> behavior
{
return
{
[self](int index)
{
aout(self) << "Worker: " << index << endl;
return index;
}
};
});
}
b_type::behavior_type bBehavior(b_type::pointer self)
{
return
{
[self](int value)
{
// Create blocking actor
scoped_actor blockingActor;
// Spawn pool workers and send each a message
auto pool = actor_pool::make(value, worker, actor_pool::round_robin());
for(int i = 0; i < value; ++i)
{
blockingActor->send(pool, i);
}
// Wait for completion
vector<int> results;
int i = 0;
blockingActor->receive_for(i, value) (
[&results](int value)
{
results.push_back(value);
});
blockingActor->send_exit(pool, exit_reason::user_shutdown);
self->quit();
return (value == results.size());
}
};
}
class A : public a_type::base
{
protected:
behavior_type make_behavior() override
{
return
{
[this](int value) -> bool
{
aout(this) << "Number of tasks: " << value << endl;
b_type forwardDestination = spawn(bBehavior);
auto castDestination = actor_cast<actor>(forwardDestination);
this->forward_current_message(castDestination);
this->quit();
return false;
}
};
}
};
void tester()
{
a_type testeeActor = spawn<A>();
scoped_actor self;
self->sync_send(testeeActor, 5).await(
[testeeActor, &self](bool success)
{
aout(self) << "All workers completed? " << (success ? "Yes!" : "No :(") << endl;
});
}
int main()
{
tester();
await_all_actors_done();
shutdown();
cout << "Press Enter to continue" << endl;
cin.get();
}
答案 0 :(得分:5)
因此,我认为直接调用forward_current_message是可以的吗?
不,forward_current_message
不属于CAF中的公共API(因此未在Doxygen中列出)。这意味着可以随时重命名,删除或成为protected
/ private
成员函数。
将消息转发给类型化演员的最佳做法是delegate
。这是一项新功能(随0.14.1引入),遗憾的是手册yet中未提及。目前可用的最佳“文档”是它在unit test for typed actors中的使用。
简短版本是:delegate
是send
的替代方案,可以转发请求的责任。在键入的actor中,您可以从消息处理程序返回delegated<T>
而不是T
,以指示其他actor将使用T
对原始发件人进行响应。
在您的情况下,类A
将实现如下:
class A : public a_type::base
{
protected:
behavior_type make_behavior() override {
return {
[this](int value) {
aout(this) << "Number of tasks: " << value << endl;
auto forwardDestination = spawn(bBehavior);
this->quit();
return delegate(forwardDestination, value);
}
};
}
};