CAF(C++ actor framework)使用隨筆(unbecome與keep_behavior用法)

看usermanual(使用隨筆一里面有)看到差很少一半的時候,這個keep_behavior與unbeacome的結合引發了個人注意。(這是爲何呢?)ios

  由於它的示例代碼寫的太簡單了!我真的沒看太懂,我就本身把他的改了改放上來。spa

先講一下,基本概念,就是一個actor能夠有多個行爲(behavior)那麼become就能夠讓一個actor變成一種行爲。3d

若是使用了keep_behavior呢就會把當前的行爲壓入「行爲棧」(behavior stack),  調用unbecome就能夠變成行爲棧上最前面的一個了。code

好比我先在行爲A的時候keep_behavior,後來我再在行爲B的時候keep_behavior一下,那麼我此時調用unbecome的時候會變成哪一個種行爲呢?答案固然是行爲B咯!
blog

貼上代碼string

#include <string>
#include <iostream>
#include "caf/io/all.hpp"
#include "caf/all.hpp"
using namespace std;
using namespace caf;

behavior testee(event_based_actor* self) {
    return {
        [=](int value1) {
            cout<<"value1:"<<value1<<endl;
                self->become (
                keep_behavior,
                [=](float value2) {
                    cout << "value2:" << value2 << endl;
                        self->become (
                        keep_behavior,
                        [=](double value3){
                            cout<<"value3:"<<value3<<endl;
                            self->unbecome();
                        }
                    );
                    });
            }
        };
}

int main(){
    auto actor1 = spawn(testee);
    {
        caf::scoped_actor self;
        int a1 = 1;
        float a2 = 1.1;
        double a3 = 1.2;
        int b1 = 2;
        float b2 = 2.1;
        double b3 = 2.2;

        self->send(actor1,a1);
        self->send(actor1,a2);
        self->send(actor1,a3);
        self->send(actor1,b1);
        self->send(actor1,b2);
        self->send(actor1,b3);
    }
    caf::await_all_actors_done();
    shutdown();
    return 0;
}

結果爲it

若是把value2循環中的keep_behavior去掉結果就是io

以後開始準備寫caf序列化方面。真的是挺好用,挺炫酷。event

最後弱弱的說一句,求互粉阿!class

相關文章
相關標籤/搜索