CAF(C++ actor framework)使用随笔(projection 用法)(一)

最近干活在写毕设,用到了CAF,看了文档,发现了一些小坑,自己摸索写点随笔。(CAF的github网站 https://github.com/actor-framework/actor-framework)里面的example文件夹例子不错。

但是感觉其实实际使用还是会有很多没讲到。

概念的东西可以看http://www.wfuyu.com/mvc/21278.html

我学习就看着http://www.actor-framework.org/manual/看下去看着不太会的就写例子,第一个坑就是3.5节的projection。

        

因为这个例子上的option是不对的,应该是optional(害我愣了一会~)

个人理解projection的意思就是 比如一个对象的回调函数期望获得一个int类型的参数传进来,但是别人给了它一个string类型的,那么projection机制就会先把他捕获,若它能够变为int就变成int被进入case1,如果不行,没关系,再用case2来捕获它就好了,毕竟人家传进来就不一定是要给case1用的。所以这个投影过程如果没成功也不是一个错误,只是说它匹配失败了。

下面贴上自己的代码 

#include <iostream>
#include "caf/all.hpp"
#include "caf/io/all.hpp"

using namespace std;
using namespace caf;

auto intproj = [](const string& str)-> optional<int> {
    char* endptr = nullptr;
    int result = static_cast<int>(strtol(str.c_str(), &endptr, 10));
    if (endptr != nullptr && *endptr == '\0') 
        return result;
    return {};
};

message_handler fun(event_based_actor* self){
    return {
        on(intproj) >> [self](int i) {
        // case 1: successfully converted a string
        aout(self)<<"projection successfully\n";
        return;
        },
        [self](const string& str) {
        // case 2: str is not an integer
        aout(self)<<"not projection \n";
        return;
        },
        after(std::chrono::seconds(2))>>[self]{
            aout(self)<<"after 2 seconds fun self is quit\n";
            self->quit();
        }
    };
}


void send_message(const actor& actor1){
    scoped_actor self;
    self->send(actor1,"1");
    self->send(actor1,"a");
}
int main(){
    auto actor1 = spawn(fun);
    send_message(actor1);    

    caf::await_all_actors_done();
    shutdown();
return 0; }

结果为

 

message_handler 和behavior 一样属于一种行为可以来生成一个actor。

CAF支持两种生成对象的方法,这里使用了最简单的以函数作为参数。

之前测试直接在main函数里用scoped_actor,那么程序就会永远等待,因为scoped_actor在函数结尾才会被quit,而

caf::await_all_actors_done();要等到所有此cpp文件中创建的actor都quit了才能继续执行下面的代码。

后来我又发现其实没必要把scoped_actor 另外搞一个函数 只要用{}把scoped_actor 包括起来就好。
就像

{
scoped_actor self;
self->send(actor1,"1");
self->send(actor1,"a");
}

在括号结束后self也会自动调用quit函数.

自己后来完了一下CAF序列,感觉功能非常的强大,直接传指针,C++中的类都不需要序列化。下次记录一下!

 
原文地址:https://www.cnblogs.com/zhejiangxiaomai/p/5238263.html