最近干活在寫畢設,用到了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++中的類都不需要序列化。下次記錄一下!
