【问题标题】:Using requests to verify command success使用请求来验证命令是否成功
【发布时间】: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&lt;void&gt;。有没有更好的方法来做到这一点?

我的备份计划是将我的命令定义更改为仅返回标准错误并在操作成功时返回sec::none。但我担心这种方法违反了整个 optional-second-parameter 对于错误条件的精神。我对这一切的思考程度如何?

    标签: c++-actor-framework


    【解决方案1】:

    有一个更好的方法吗?

    你有正确的想法。 result&lt;void&gt; 期望错误或“无效”值。由于void{} 不是 C++ 中的东西,您可以使用return caf::unit; 告诉result&lt;void&gt; 构造一个“空”结果。在接收方,您已经做了正确的事情:then 使用不带参数的 lambda。

    小点:

    [=](void) { ... }
    

    这是早期的 C 主义,编译器允许你做一些愚蠢的事情。只需删除void,它没有任何用处。 :)

    【讨论】:

    • 那行得通!做得好!!
    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 2015-09-08
    • 2015-12-04
    • 1970-01-01
    • 2014-12-09
    • 2018-12-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多