我正在尝试将一些工作从一个打字演员移交给另一个演员。CAF 用户手册表明这可以使用该forward_to
方法完成。该方法看起来仅适用于显式event_based_actor
类型的参与者。但是,forward_to
似乎是对该方法的一个薄包装,该forward_current_message
方法是为该local_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();
}