您的位置:首页 > 编程语言 > C语言/C++

CAF(C++ actor framework)使用随笔(同步发送 异步与同步等待)(三)

2016-03-06 11:24 706 查看
c). 同步发送, 等待响应, 超时后收到1个系统消息.

贴上代码

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

behavior fun(event_based_actor* self){
return {
[self](const string& str, const actor &buddy)->string {
aout(self)<<str<<endl;
//self->delayed_send(buddy,std::chrono::milliseconds(10),"I'm lated");
//std::this_thread::sleep_for(std::chrono::seconds(1));
//usleep(10000);
while(1);
return "log";
self->quit();
}
};
}

void fun1(event_based_actor* self, const actor &buddy){
self->sync_send(buddy,"hi!",self).then(
[=](const string& str) {
aout(self)<<str<<endl;
},
after(std::chrono::milliseconds(1))>>[&](){
aout(self)<<"timeout!"<<endl;
}
);
aout(self)<<"i'm not waiting for you!"<<endl;
}

int main(){
auto actor1 = spawn(fun);
auto actor2 = spawn(fun1,actor1);
caf::await_all_actors_done();
shutdown();
return 0;
}


其中自己试了几种线程休息的几种方法,发现usleep和 C++11自己提供的线程休眠库会导致coredump并且输出一堆东西,可能是caf自己的东西没有去深究等,

还有就是delay_send我也一开始有点傻,想用delay_send去回复发过来的消息,所以传入了actor,但是要搞清楚“发送”和“回复”是两种东西,你不能用发送来回复,只能用return来回复



d). 同步发送, 同步等待. 适用阻塞的actor api.

#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)->string {
aout(self)<<str<<endl;
return "I got it.";
//self->quit();
}
};
}

void fun1(blocking_actor* self, actor buddy){
self->sync_send(buddy,"hi!").await(
[=](const string& str) {
aout(self)<<str<<endl;
},
after(std::chrono::milliseconds(1))>>[&](){
aout(self)<<"timeout!"<<endl;
}
);
aout(self)<<"i'm not waiting for you!"<<endl;
}

int main(){
auto actor1 = spawn(fun);
auto actor2 = spawn<blocking_api>(fun1,actor1);
caf::await_all_actors_done();
shutdown();
return 0;
}


结果(顺序变了)为


唯一修改就是spawn那边加上类型。

自己写了一个很简陋的聊天 传文件的程序,有兴趣可以看一下,维护好友列表,心跳机制都是用caf实现,当时没有用caf的序列话 用的是boost库的。
https://github.com/zhejiangxiaomai/chat
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: