【发布时间】:2022-03-24 15:22:36
【问题描述】:
假设 Typed Actor A 需要命令 Typed Actor B 做某事。参与者 A 还需要知道命令是否成功运行,但在此响应到达之前不希望阻止操作。我目前的工作理论是Requests 最满意。更具体地说request(...).then
我一直在玩一个很好的例子,叫做“request.cpp”。我的挑战是我真的不需要演员 B 返回任何数据。我只需要知道命令是否成功,如果不成功,会引发什么错误。
所以我的问题有两个方面:1)我认为request(...).then 是做我想做的事情的正确机制是否正确,2)如果是这样,那么请求可以处理没有数据的响应吗?
这就是我正在尝试的:
#include <chrono>
#include <cstdint>
#include <iostream>
#include <vector>
#include \"caf/all.hpp\"
using std::endl;
using std::vector;
using std::chrono::seconds;
using namespace caf;
using cell
= typed_actor<result<void>(get_atom, int32_t)>;
struct cell_state {
static constexpr inline const char* name = \"cell\";
cell::pointer self;
cell_state(cell::pointer ptr) : self(ptr) {}
cell_state(const cell_state&) = delete;
cell_state& operator=(const cell_state&) = delete;
cell::behavior_type make_behavior() {
return {
[=](get_atom, int32_t input) -> result<void> {
if (input != 5) { // Simulate command successful or not
return; // If successful, then return;
}
else {
return sec::unexpected_message; // If not then return error.
}
},
};
}
};
using cell_impl = cell::stateful_impl<cell_state>;
void multiplexed_testee(event_based_actor* self, vector<cell> cells) {
for (cell& x : cells) {
aout(self) << \"cell #\" << x.id() << \" calling\" << endl;
self->request(x, seconds(1), get_atom_v, static_cast<int32_t>(x.id()))
.then(
[=](void) {
aout(self) << \"cell #\" << x.id() << \" -> \" << \"success\" << endl;
},
[=](error& err) {
aout(self) << \"cell #\" << x.id() << \" -> \" << to_string(err) << endl;
});
}
}
void caf_main(actor_system& system) {
vector<cell> cells;
for (int32_t i = 0; i < 5; ++i)
cells.emplace_back(system.spawn<cell_impl>());
scoped_actor self{ system };
auto x2 = self->spawn(multiplexed_testee, cells);
self->wait_for(x2);
}
CAF_MAIN()
当我编译时,我在空的返回语句上得到一个错误,说“返回语句没有值,在函数返回caf::result<void>。有没有更好的方法来做到这一点?
我的备份计划是将我的命令定义更改为仅返回标准错误并在操作成功时返回sec::none。但我担心这种方法违反了整个 optional-second-parameter 对于错误条件的精神。我对这一切的思考程度如何?