项目地址:https://github.com/wlgq2/orca
orca的邮箱
当Actor对象被构造时,orca会为其申请一个邮箱,用于消息通信。当Actor对象被析构后,orca会回收该邮箱并用于其他新申请Actor对象。orca通过索引来分配、回收邮箱。其中申请邮箱的时间复杂度为o(1),回收的实现复杂度为o(logN)。
图:orca邮箱结构
消息发送与接收
orca消息通信接口很简单,只需要对相应的Actor发送消息,并注册该Actor的消息处理函数即可。
发送消息:
void send(const MessagePack<MessageType>& message,Address& destination);
或者通过Actor的名字发送消息:
void send(const MessagePack<MessageType>& message, std::string& name);
注册消息处理函数接口:
void registerHandler(ActorHandle handler);
一个完整的例子:
#include <iostream>
#include <orca/orca.h>
REGISTER_MESSAGE_TYPE(std::string);
class ActorTest :public orca::Actor
{
public:
ActorTest(orca::Framework* framework,std::string name = "")
:Actor(framework, name)
{
registerHandler(std::bind(&ActorTest::handle,this,std::placeholders::_1,std::placeholders::_2));
}
void handle(orca::MessagePack& pack, orca::Address& from)
{
std::cout << (char*)(pack.enter()) << std::endl;
}
};
int main(int argc, char** args)
{
//actor framework.
orca::Framework framework;
//arctor object.
ActorTest actor1(&framework);
ActorTest actor2(&framework,"actor02");
//message pack.
orca::MessagePack message;
message.create("a message to actor2");
//actor1->actor2 send message.
actor1.send(message,"actor02");
framework.loop();
}