a). 發完就忘, 就像上面anon_send 以及sendios
#include <iostream> #include "caf/all.hpp" #include "caf/io/all.hpp" #include <string> using namespace std; using namespace caf; behavior fun(event_based_actor* self){ return { [self](const string& str,actor a) { aout(self)<<"get message: "<<str<<endl; //get the actor a's address aout(self)<<to_string(a.address())<<endl; // send message anonymously anon_send(a,"hello"); // get lastest current message aout(self)<<"current_message: "<<to_string(self->current_message())<<endl; aout(self)<<"current_sender: "<<to_string(self->current_sender())<<endl; self->quit(); return; } }; } int main(){ auto actor1 = spawn(fun); { scoped_actor self; self->send(actor1,"anon_send",self); //wrong code scoped_actor do not have anon_send and become function // self->become( // [=](const string& str){ // aout(self)<<"get message: "<<str<<endl; // ); } caf::await_all_actors_done(); shutdown(); return 0; }
結果圖:c++
發現scoped_actor 不能使用anon_send 和becoem函數,但我我的理解scoped的send就是anon的發送,發完他就消失了。異步
b).同步發送, 等待響應. 等待是異步的, 至關於只是期待1個響應.函數
貼上代碼ui
#include <iostream> #include "caf/all.hpp" #include "caf/io/all.hpp" #include <string> using namespace std; using namespace caf; behavior fun(event_based_actor* self){ return { [self](const string& str) { self->quit(); return "hello, world"; } }; } void fun1(event_based_actor* self, const actor &buddy){ self->sync_send(buddy,"hi!").then( [=](const string& str) { aout(self)<<str<<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; }
結果爲spa
其實這裏遇到兩個小問題,第一個就是做爲參數傳入的actor buddy必須定義爲const,否則編譯會報錯,第二個問題,我本身認爲這個代碼的結果應該會須要我ctrl+C去結束。結果,我發現actor2在接受到這個消息以後跑完也就調用quit()了,那麼我本身就把then()裏面的代碼註釋起來,再編譯經過了,運行的時候就coredump了。想到了c++11裏面 若是線程不join也會發生coredump。因此仍是要注意這個問題,目前還沒講異常處理。線程
--------------------------------------------------3.15 更新線-----------------------------------------------------------c++11
發現一個bug 就是兩個進程通信時(使用remoter actor的狀況下!),假設又兩個進程A,B 當A 使用send 發給B 一個message 的時候,B會收到這個message,可是不會收到這個傳過來的message內容,而使用sync_send 無論是await也好then 也好都是可讓B收到消息的內容的。那麼第二次再send 或者sync_send時 卻都是同樣的。那我一開始理解爲publish 一個端口時會須要花費一些時間,因此send發過來沒收到,可是sync_send卻能夠,因此我認爲應該是一個bug吧code