CAF(C++ actor framework)使用随笔(延迟发送,消息转发,消息优先级)

Posted 浙江小麦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CAF(C++ actor framework)使用随笔(延迟发送,消息转发,消息优先级)相关的知识,希望对你有一定的参考价值。

e). 消息延迟发送(和前面没太大区别直接上代码)

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


behavior fun(event_based_actor* self){
    return {
        [self](const string& str){
            aout(self)<<str<<endl;
            auto t2 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
            cout<<"dalay time :"<<t2<<endl;
            self->quit();
            }
    };
}

void fun1(event_based_actor* self, actor buddy){
    self->delayed_send(buddy, std::chrono::seconds(1), "hi!");
}

int main(){
    auto actor1 = spawn(fun);
    auto t1 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    cout<<"before delayed_send :"<<t1<<endl;
    auto actor2 = spawn(fun1,actor1);

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

结果为

技术分享

 f). 消息前转(消息转发)forward.

贴上代码

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

behavior fun2(event_based_actor* self){
    return {
        [self](const string& str){
            aout(self)<<"C get message return to A"<<endl;
            aout(self)<<"C‘s address is :"<<self->address()<<endl;
            return "hello, A";
            self->quit();
         }
    };
}

behavior fun1(event_based_actor* self, const actor &buddy){
    return {
        [=](const string& str){
            aout(self)<<"B get message forward to C"<<endl;
            self->forward_to(buddy);
            self->quit();
         }
    };
}

void fun(event_based_actor* self, const actor &buddy){
    self->sync_send(buddy,"hi!").then(
         [=](const string& str) {
             aout(self)<<str<<endl;
             aout(self)<<"A think last_sender is :"<<self->last_sender()<<endl;
         }
    );
    aout(self)<<"A send to B!"<<endl;
}

int main(){
    auto actorC = spawn(fun2);
    auto actorB = spawn(fun1,actorC);
    auto actorA = spawn(fun,actorB);
    caf::await_all_actors_done();
    shutdown();
    return 0;
}

结果为

技术分享

以上是关于CAF(C++ actor framework)使用随笔(延迟发送,消息转发,消息优先级)的主要内容,如果未能解决你的问题,请参考以下文章

CAF(C++ actor framework)使用随笔(各种send通信用法)

C++ Actor并发模型框架 Actor Framework (CAF)

CAF(C++ actor framework)使用随笔(延迟发送,消息转发,消息优先级)

CAF(C++ actor framework)(序列化之类,无需序列化,直接传)

CAF(C++ actor framework)使用随笔(unbecome与keep_behavior用法)

我可以在 C++ Actor Framework 中使用 C++11 智能指针作为消息返回类型吗?