1. 程式人生 > 其它 >聊聊filezilla 3.7.2 事件處理機制

聊聊filezilla 3.7.2 事件處理機制

  filezilla 3.7.2 處理事件依賴於一個自己封裝的事件處理器。名字叫event_loop類。 這個類在libfillezilla工程種。作為filezilla的一個動態庫。因為這個處理器對於filezilla十分重要。所以藉此機會學習以下。 

  event_loop 標頭檔案在 libfilezilla工程目錄\lib\libfilezilla\event_loop.hpp。 cpp在 libfilezilla\lib\event_loop.cpp。和event_loop關係密切的一個類是event_handler。位置與event_loop相同。 這個類是對event_loop的一個薄層封裝。

  event_loop 支援兩種,一種是事件類(event)的。另外一種是時間類(timer)的。

  對於怎麼使用event_loop,libfillezilla中有對應的例子。程式碼中也有簡潔的類。以libfilezilla工程demo_events 為例。demo_events工程 只有一個叫events.cpp 的檔案。程式碼十分簡單。如下

 1 // Define a new event.
 2 // The event is uniquely identified via the incomplete my_event_type struct and
 3 // has two arguments: A string and a vector of ints.
4 struct my_event_type; 5 typedef fz::simple_event<my_event_type, std::string, std::vector<int>> my_event; 6 7 // A simple event handler 8 class handler final : public fz::event_handler 9 { 10 public: 11 handler(fz::event_loop& l) 12 : fz::event_handler(l) 13 {}
14 15 virtual ~handler() 16 { 17 // This _MUST_ be called to avoid a race so that operator()(fz::event_base const&) is not called on a partially destructed object. 18 remove_handler(); 19 } 20 21 private: 22 // The event loop calls this function for every event sent to this handler. 23 virtual void operator()(fz::event_base const& ev) 24 { 25 // Dispatch the event to the correct function. 26 fz::dispatch<my_event>(ev, this, &handler::on_my_event); 27 } 28 29 void on_my_event(std::string const& s, std::vector<int> const& v) 30 { 31 std::cout << "Received event with text \"" << s << "\" and a vector with " << v.size() << " elements" << std::endl; 32 33 // Signal the condition 34 fz::scoped_lock lock(m); 35 c.signal(lock); 36 } 37 };

 

可以看出,要使用event_loop類,需要實現自己的 event_handler類函式。在自己的event_handler類中需要做以下幾件事。

  1 定義構造 解構函式

  2 定義自己simple_event 的資料型別 以及這種資料型別的處理函式。

  3 定義自己仿函式(或者叫()過載運算子)。

呼叫也很簡單,程式碼如下。  

 1 // Start an event loop
 2 fz::event_loop l;
 3 
 4 // Create a handler
 5 handler h(l);
 6 
 7 // Send an event to the handler
 8 h.send_event<my_event>("Hello World!", std::vector<int>{23, 42, 666});
 9 
10 // Wait until a signal from the worker thread
11 fz::scoped_lock lock(m);
12 c.wait(lock);  

定義 fz::event_loop 類例項,用這個例項構造handler 例項。呼叫handler 的send_event函式函式。

此處省略100字,明天分析event_loop 如何執行的。